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

tryCatch()

In this page:

  1. tryCatch()

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")
🔒

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.