0Pricing
R Academy · Lesson

tryCatch() for Error Recovery

Catch and handle errors, warnings, and messages with tryCatch().

What is tryCatch()?

tryCatch() lets you run an expression and intercept any conditions (errors, warnings, messages) that it signals. If the expression succeeds, its value is returned. If it signals a condition, the matching handler is called instead.

result <- tryCatch({
  sqrt(16)
}, error = function(e) {
  NA
})
cat('Result:', result, '\n')

Catching an Error

When the expression inside tryCatch() calls stop(), execution jumps to the error handler. The handler receives the condition object and returns its value as the result of the whole tryCatch() call.

safe_divide <- function(x, y) {
  tryCatch({
    if (y == 0) stop('division by zero')
    x / y
  }, error = function(e) {
    cat('Caught error:', conditionMessage(e), '\n')
    NA
  })
}
cat(safe_divide(10, 2), '\n')
cat(safe_divide(10, 0), '\n')

All lessons in this course

  1. Errors, Warnings, and Messages in R
  2. tryCatch() for Error Recovery
  3. withCallingHandlers() and Restarts
  4. Writing Robust Functions with stop() and warning()
← Back to R Academy