← Back to R Course | Chapter 12: Best Practices | Lesson 5 of 6

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:

  1. tryCatch()
Syntax
r
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()

markup
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")
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
  1. Forgetting that a warning is not caught by error =, so it needs a warning = function(w) handler.
  2. Putting the expression outside tryCatch(...), so the error is not caught.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.