tryCatch has a slightly complex syntax structure. However, once we understand the 4 parts which constitute a complete tryCatch call as shown below, it becomes easy to remember:
expr: [Required] R code(s) to be evaluated
error : [Optional] What should run if an error occured while evaluating the codes in expr
warning : [Optional] What should run if a warning occured while evaluating the codes in expr
finally : [Optional] What should run just before quitting the tryCatch call, irrespective of if expr ran successfully, with an error, or with a warning
tryCatch( expr = { # Your code... # goes here... # ... }, error = function(e){ # (Optional) # Do this if an error is caught... }, warning = function(w){ # (Optional) # Do this if a warning is caught... }, finally = { # (Optional) # Do this at the end before quitting the tryCatch structure... } )
Thus, a toy example, to calculate the log of a value might look like:
log_calculator <- function(x){ tryCatch( expr = { message(log(x)) message("Successfully executed the log(x) call.") }, error = function(e){ message('Caught an error!') print(e) }, warning = function(w){ message('Caught an warning!') print(w) }, finally = { message('All done, quitting.') } ) }
Now, running three cases:
A valid case
log_calculator(10) # 2.30258509299405 # Successfully executed the log(x) call. # All done, quitting.
A "warning" case
log_calculator(-10) # Caught an warning! # <simpleWarning in log(x): NaNs produced> # All done, quitting.
An "error" case
log_calculator("log_me") # Caught an error! # <simpleError in log(x): non-numeric argument to mathematical function> # All done, quitting.
I've written about some useful use-cases which I use regularly. Find more details here: Using tryCatch for robust R scripts
Hope this is helpful.