tryCatch()
In this page:
tryCatch()
tryCatch(expr, error = function(e) ...) runs an expression and lets you handle an error gracefully instead of letting it crash the script, similar to try/catch in other languages. It also supports warning and finally handlers. This is essential for scripts that process data which might occasionally be malformed, allowing them to continue rather than stopping entirely.
Note: The error handler receives the error object itself, so e$message inside it gives you the underlying error text.
Example: tryCatch()
safe_divide <- function(a, b) {
tryCatch({
if (b == 0) stop("Division by zero")
a / b
}, error = function(e) {
cat("Error caught:", e$message, "\n")
NA
})
}
cat(safe_divide(10, 2), "\n")
cat(safe_divide(10, 0), "\n")
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: