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')