tryCatch()
tryCatch is a safety net for code that might go wrong: try something, and if it fails run a backup plan instead of crashing. It lets your program handle mistakes gracefully.
In this page:
Syntax
result <- tryCatch({
expression
}, error = function(e) {
# handle error
}, finally = {
# always runs
})
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting that a
warningis not caught byerror =, so it needs awarning = function(w)handler. - Putting the expression outside
tryCatch(...), so the error is not caught. - Ignoring the error and returning nothing, so the caller does not know that something went wrong.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: