Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Control Flow and Functions

Errors, Warnings and Debugging in R

Handle problems in R code. Raise errors with stop(), warn with warning(), catch them with tryCatch() and try(), clean up with finally, and debug with traceback() and browser().

Code fails. A file is missing, a column has text where you expected numbers, a calculation produces something undefined. What matters is what your program does next. A script that dies halfway through a two-hour analysis because of one bad value is frustrating. A script that notes the problem, skips that value and carries on is useful.

This lesson covers the three kinds of conditions R signals, how to catch them with tryCatch(), and a debugging toolkit for finding the bugs you did not expect.

Errors, warnings and messages

R signals problems at three levels. You met them in Getting Help; now you will create them yourself.

R
check_age <- function(age) {
  if (age < 0) {
    stop("age cannot be negative")       # error: stops everything
  }
  if (age > 120) {
    warning("age above 120 looks odd")   # warning: continues
  }
  message("age checked")                 # message: information
  age
}

check_age(130)
#> age checked
#> [1] 130
#> Warning message:
#> In check_age(130) : age above 120 looks odd
Function Effect Use it when
stop("text") Halts the function, signals an error The result would be wrong or impossible
warning("text") Continues, reports at the end Something questionable but survivable
message("text") Prints to the message stream Progress and information

stopifnot() is a shortcut for assertions: stopifnot(is.numeric(x), x > 0) stops with an automatic message naming the failed condition.

tryCatch: handling conditions

tryCatch() runs an expression and lets you supply handlers for the conditions it signals:

R
tryCatch(
  expr    = stop("boom"),
  error   = function(e) conditionMessage(e)
)
#> [1] "boom"

The handler receives a condition object; conditionMessage(e) extracts its text. The value of tryCatch() is either the value of the expression (if it succeeded) or the value returned by the handler (if a condition occurred).

Warnings can be handled the same way:

R
tryCatch(
  log(-1),
  warning = function(w) "negative input"
)
#> [1] "negative input"

A realistic pattern is converting input and falling back to a default:

R
to_number <- function(text) {
  tryCatch(
    as.numeric(text),
    warning = function(w) NA_real_
  )
}

to_number("42")
#> [1] 42

to_number("forty")
#> [1] NA

Without the handler, as.numeric("forty") would return NA but also print a warning. Handling it makes the intent explicit and keeps the console clean.

finally: always clean up

The finally argument runs whether or not anything went wrong, which suits closing files and connections:

R
tryCatch(
  {
    cat("working\n")
    stop("oops")
  },
  error   = function(e) cat("caught:", conditionMessage(e), "\n"),
  finally = cat("cleanup\n")
)
#> working
#> caught: oops 
#> cleanup

Inside functions, on.exit(close(con)) registers cleanup that runs when the function ends for any reason.

try: the short version

try() runs an expression and, instead of stopping the script on an error, returns an object of class "try-error":

R
res <- try(log("a"), silent = TRUE)
class(res)
#> [1] "try-error"

inherits(res, "try-error")
#> [1] TRUE

log("a") fails with non-numeric argument to mathematical function. With silent = TRUE that message is not printed. try() is quick for one-off protection; tryCatch() gives finer control.

Keep going over a batch

A very common use is processing many items and not letting one failure stop the rest:

R
inputs <- c("10", "x", "30")

results <- sapply(inputs, function(s) {
  tryCatch(as.integer(s), warning = function(w) NA_integer_)
})
results
#> 10  x 30 
#> 10 NA 30 

Use sapply() or a loop, wrap the risky call, and decide what a failed item should produce. Log the failures so that skipped items are not forgotten silently.

flowchart TD
    A["Run expression"] --> B{"Condition signaled?"}
    B -- "no" --> C["Return the value"]
    B -- "error or warning" --> D["Run matching handler"]
    D --> E["Return handler value"]
    C --> F["finally block runs"]
    E --> F

Figure: the path through tryCatch().

Do not swallow errors blindly. A handler like error = function(e) NULL hides real bugs. Handle the specific problem you expect, and log or rethrow anything else. If you catch an error and discard it, someone will spend hours wondering why results are missing.

Debugging: finding bugs you did not expect

Error handling covers problems you can predict. For everything else you debug.

1. Read the message and locate the line

Start with the error text and the call it names. Then run the code a line at a time. Most bugs are a variable that is not what you assumed, so inspect with str(x), class(x), length(x) and head(x).

2. traceback()

After an error inside nested functions, call traceback() (in RStudio, click "Show Traceback"). It lists the chain of calls, innermost first, so you see where the failure happened.

3. Print debugging

Insert cat("x is", x, "\n") or print(str(df)) at suspicious points. It is crude and effective, especially in loops. Remove the prints afterwards.

4. browser() and debug()

browser() pauses execution at that line and gives you an interactive prompt where you can inspect variables:

R
f <- function(x) {
  y <- x * 2
  browser()          # execution stops here
  y + 1
}

At the Browse[1]> prompt, type a variable name to see it, n to run the next line, c to continue and Q to quit. debug(f) starts the debugger at the beginning of f the next time it is called (turn off with undebug(f)), and debugonce(f) does so for one call. In RStudio you can also click in the margin to set a breakpoint and use the debug toolbar.

5. Shrink the problem

Reduce your input until the bug is small enough to see. Use a handful of rows or a three-element vector. This is also the first step of writing the reproducible example described in Getting Help.

Useful habits

  • Validate inputs at the top of each function (stopifnot(), stop()).
  • Prefer clear error messages that say what was expected and what was found.
  • Test small functions separately before combining them.
  • After fixing a bug, keep the example that exposed it as a test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between stop() and warning()?

    An error ends the function (unless caught); a warning is reported and the code continues.
  2. 2. What does tryCatch(stop("x"), error = function(e) 5) return?

    The error handler runs and its return value becomes the value of tryCatch.
  3. 3. When does the finally block of tryCatch() run?

    finally is for cleanup that must always happen.
  4. 4. What does class(try(log("a"), silent = TRUE)) show?

    try() returns an object of class try-error when the expression fails.
  5. 5. What does browser() do?

    It starts an interactive debugging session at the point where it is called.

Summary

  • stop() raises errors, warning() raises warnings, message() informs; stopifnot() asserts.
  • tryCatch() catches conditions with handlers and runs finally for cleanup; try() is the quick version.
  • Wrap risky steps inside sapply() or loops so one failure does not stop the batch, but never hide errors silently.
  • Debug by reading messages, inspecting with str(), using traceback(), print statements, browser() and RStudio breakpoints.
  • Shrink the failing case to the smallest example.

Next: Data Frames