Use the try
command.
Normally this will cause an error and prevent code that comes afterwards from running:
x <- "a" + 1
y <- 1
y
However, if we wrap the part after the assignment operator in try
, the error prints but code written afterwards can still run:
x <- try("a" + 1)
y <- 1
y
Note that x
has class "try-error"
class(x)
"try-error"
Therefore in your example, you could do the following to make sure later lines run whilst still being able to pick up that earlier lines failed:
x <- try(sqlQuery(myConn,"exec sp_v_table_3"))
y <- 1
y
class(x)
The object y
will still be created, and the class of x
will tell you whether sqlQuery(myConn,"exec sp_v_table_3")
ran successfully or not.
tryCatch
is in a sense a more flexible version of try
. try
will only return class "try-error"
if an error occurs and allow later lines of code to run, but tryCatch
will allow you to specify what you want to happen if an error occurs. You could also specify what you want to happen if a warning
occurs or even if the code runs successfully.
And purrr::safely
is a wrapper around tryCatch
. There the action specified upon an error is to return a list with two elements: alternate output (by default NULL
) and the error message.