Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Advanced R

Error Handling and Debugging in R: tryCatch, stop, browser

Handle problems in R code: messages, warnings and errors, stop(), tryCatch(), finally, custom conditions, on.exit(), stopifnot(), and debugging with traceback(), browser() and debug().

Code fails. A file is missing, a network call times out, a user types text where a number belongs. What separates a script from a reliable program is what happens next: does the failure produce a clear message, can the program recover, and can you find the cause quickly? This lesson covers both halves: handling conditions in code and debugging when something unexpected happens.

R is not available on this site, so the R code is read-only. Results shown are the standard behavior of these calls. A Python block at the end shows the same ideas so you can run something.

Three kinds of conditions

R signals problems through conditions, and there are three levels of severity:

Function Severity What happens
message("...") information printed to the console (stderr), code continues
warning("...") something is suspicious collected and shown, code continues
stop("...") the function cannot continue execution stops, the call stack unwinds
R
safe_divide <- function(a, b) {
  if (!is.numeric(a) || !is.numeric(b)) stop("both arguments must be numeric")
  if (b == 0) {
    warning("division by zero, returning NA")
    return(NA_real_)
  }
  a / b
}
safe_divide(10, 4)       # 2.5
safe_divide(1, 0)        # NA, with a warning
safe_divide("a", 2)      # Error in safe_divide("a", 2) : both arguments must be numeric

Write error messages for the person who will read them: say what was wrong and what was expected ("b must be a single positive number, not a character vector"). Use call. = FALSE in stop() to hide the technical call when the user-facing message is enough.

Validating input early

Check the inputs at the top of a function, so that failures happen early and close to the cause:

R
stopifnot(is.numeric(x), length(x) > 0)
stopifnot("x must be positive" = all(x > 0))     # named condition: R 4.0+ uses the name as message

stopifnot() stops with a message naming the failed expression. Give each condition a name for a friendlier message. Also useful: match.arg(type) to restrict an argument to a set of choices, and missing(arg) to test for omitted arguments.

tryCatch(): recover from conditions

tryCatch(expr, ...) evaluates expr; if a condition of a named class occurs, the matching handler runs instead and its value becomes the result.

R
tryCatch(stop("boom"), error = function(e) conditionMessage(e))      # "boom"
tryCatch(log(-1), warning = function(w) "warned")                    # "warned"
tryCatch(as.integer("x"), warning = function(w) conditionMessage(w))
# "NAs introduced by coercion"

A full pattern, with the three parts you will use all the time:

R
result <- tryCatch(
  {
    cat("working\n")
    risky_operation()
  },
  error = function(e) {
    message("failed: ", conditionMessage(e))
    NA
  },
  finally = {
    cat("cleanup\n")           # always runs, success or failure
  }
)

finally is for cleanup (close a connection, remove a temp file). Without errors you would see working then cleanup and result holds the return value; with an error you would see the message, then cleanup, and result is NA.

tryCatch() exits the calculation as soon as the condition occurs. To log a warning and keep going, use withCallingHandlers() and tell R to resume:

R
withCallingHandlers(
  {
    warning("w1")
    "done"
  },
  warning = function(w) {
    message("log: ", conditionMessage(w))
    invokeRestart("muffleWarning")      # continue as if nothing happened
  }
)
# prints "log: w1" and returns "done"

There are shortcuts: suppressWarnings(expr) and suppressMessages(expr) silence everything, which is risky; prefer to handle the specific one you expect. The older try(expr, silent = TRUE) returns an object of class "try-error" on failure, and inherits(res, "try-error") tests for it.

A retry loop

Real programs retry flaky operations:

R
fetch_with_retry <- function(f, attempts = 3) {
  for (i in seq_len(attempts)) {
    out <- tryCatch(f(), error = function(e) NULL)
    if (!is.null(out)) return(out)
    message("attempt ", i, " failed")
  }
  stop("all ", attempts, " attempts failed")
}

Custom conditions

A condition is just an object whose class vector starts with your own class and ends with "error" (or "warning") and "condition". Handlers can then catch exactly your problem and nothing else:

R
validation_error <- function(msg, data = NULL) {
  structure(class = c("validation_error", "error", "condition"),
            list(message = msg, call = sys.call(-1), data = data))
}

res <- tryCatch(
  stop(validation_error("bad input", data = 5)),
  validation_error = function(e) paste("caught:", conditionMessage(e))
)
res     # "caught: bad input"

Catching error broadly hides bugs (a typo gives the same error class as a network failure). Catch specific classes and let everything else go through.

Cleaning up: on.exit()

on.exit() registers code to run when the function ends, however it ends:

R
read_temp <- function(path) {
  con <- file(path, "r")
  on.exit(close(con), add = TRUE)     # runs even if the next line errors
  readLines(con)
}

add = TRUE appends to earlier on.exit() calls instead of replacing them. It is the R equivalent of finally or with in other languages.

Debugging

A bug is a difference between what you expected and what happened. A methodical approach beats guessing:

  1. Reproduce it with the smallest input possible.
  2. Locate it: which line first produces a wrong value?
  3. Fix the cause, not the symptom, then add a test so that it stays fixed.

Tools

R
traceback()             # after an error: the chain of calls that led to it
debug(my_function)      # step through my_function line by line on its next call
undebug(my_function)
debugonce(my_function)  # debug the next call only
browser()               # put inside the code: execution pauses here
options(error = recover)  # on any error, choose a stack frame to inspect

Inside the debugger (Browse[1]>), type n for the next line, s to step into a call, c to continue, Q to quit, and any R expression to inspect variables. RStudio shows the same as buttons and a breakpoint gutter. print(x), str(x) and message("x is ", x) ("print debugging") are still often the fastest tools; remove them afterwards.

The usual suspects

  • Type surprises: a column is a factor, not text (str(df) shows it). Reading a CSV may turn numbers into characters if one cell is "N/A".
  • NA propagation: one NA makes sums and means NA; anyNA(x) finds out.
  • Recycling: c(1,2,3) + c(10,20) recycles with only a warning.
  • Floating point: 0.1 + 0.2 == 0.3 is FALSE; use isTRUE(all.equal(0.1 + 0.2, 0.3)).
  • Off-by-one and empty vectors: 1:length(x) is c(1, 0) when x is empty; use seq_along(x).
  • Scope: a function reads a global variable you forgot about.

Asking for help

If you are stuck, create a reproducible example: a few lines that build a tiny data set (dput(head(df)) prints one) and trigger the problem; run sessionInfo() and include the output. The reprex package formats the result for forums.

The same ideas in Python

Python's try/except/finally, custom exception classes and contextlib correspond to tryCatch, custom conditions and on.exit(). Run this comparison.

Python Python comparison: handling errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Catching every error with tryCatch(expr, error = function(e) NULL) and never noticing the failure.
  • Using suppressWarnings() on a whole script.
  • Using 1:length(x) instead of seq_along(x).
  • Leaving browser() or debug() calls in finished code.
  • Comparing floating point numbers with ==.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the finally argument of tryCatch() do?

    finally is for cleanup that must happen no matter how the expression ended.
  2. 2. Which function lets you log a warning and then continue the computation?

    tryCatch() unwinds the stack when it catches a condition. withCallingHandlers() runs the handler and can resume.
  3. 3. Why is seq_along(x) safer than 1:length(x)?

    1:length(x) for an empty vector gives c(1, 0) and the loop body runs twice. seq_along() returns integer(0).
  4. 4. Which call pauses execution inside a function so you can inspect variables?

    browser() opens the interactive debugger at that point.

Summary

  • message(), warning() and stop() signal conditions of rising severity; validate inputs early with stopifnot().
  • tryCatch(expr, error =, warning =, finally =) recovers; withCallingHandlers() observes and resumes.
  • Custom condition classes let you catch exactly your problem; on.exit() guarantees cleanup.
  • Debug by reproducing, locating (traceback(), browser(), debug()), then fixing the cause.
  • Watch for type surprises, NAs, recycling, floating point and empty vectors.

Next: Performance and Packages in R