TExcelTAD
Home › R › R Error Handling

R Error Handling

Things go wrong: a file is missing, a value can't be converted, a model doesn't converge. R signals problems with conditions of three kinds:

Condition Created with Effect if not handled
message message() text is shown, code continues
warning warning() a warning is shown, code continues
error stop() execution stops

Raising conditions

Use stop() when your function cannot continue, and warning() when it can but the caller should know something is off:

r · try it yourself
sqrt_checked <- function(x) {
  if (!is.numeric(x)) stop("x must be numeric")
  if (any(x < 0)) warning("negative values replaced by NA")
  x[x < 0] <- NA
  sqrt(x)
}
sqrt_checked(c(4, -1, 9))
sqrt_checked("nine")
cat("This line is never reached\n")
[1]  2 NA  3
Warning message:
In sqrt_checked(c(4, -1, 9)) : negative values replaced by NA
Error in sqrt_checked("nine") : x must be numeric

The warning appears after the statement that raised it, and the error message names the call where it happened. The error stopped the script.

Validating arguments with stopifnot()

stopifnot() checks several conditions at once and produces a clear error for the first that fails. Naming the conditions gives custom messages:

r · try it yourself
area <- function(width, height) {
  stopifnot(
    "width must be a number" = is.numeric(width),
    "height must be positive" = height > 0
  )
  width * height
}
area(3, 4)
area(3, -1)
[1] 12
Error in area(3, -1) : height must be positive

Catching errors with tryCatch()

tryCatch() runs an expression and, if a condition occurs, calls the matching handler instead of stopping. The handler's return value becomes the result:

r · try it yourself
parse_number <- function(text) {
  tryCatch(
    {
      value <- suppressWarnings(as.numeric(text))
      if (is.na(value)) stop("not a number: ", text)
      value
    },
    error = function(e) {
      cat("Problem:", conditionMessage(e), "\n")
      NA
    }
  )
}
parse_number("42.5")
parse_number("forty")
cat("The script keeps running\n")
[1] 42.5
Problem: not a number: forty
[1] NA
The script keeps running

as.numeric("forty") returns NA (with a warning that we silence with suppressWarnings()), so the block raises its own error with a clearer message. The handler catches that error, prints the message and returns NA, and the script keeps going.

Handling warnings and finally

Handlers exist for warning, message and error. The finally block runs whatever happens, which is ideal for clean-up such as closing connections:

r · try it yourself
safe_log <- function(x) {
  tryCatch(
    log(x),
    warning = function(w) {
      cat("Warning caught:", conditionMessage(w), "\n")
      NaN
    },
    error = function(e) {
      cat("Error caught:", conditionMessage(e), "\n")
      NA
    },
    finally = cat("-- done with", deparse(x), "\n")
  )
}
safe_log(100)
safe_log(-1)
safe_log("a")
-- done with 100
[1] 4.60517
Warning caught: NaNs produced
-- done with -1
[1] NaN
Error caught: non-numeric argument to mathematical function
-- done with "a"
[1] NA

Notice that the finally text appears before each result: it runs as tryCatch() finishes, and the returned value is auto-printed afterwards.

try(): the quick version

try() evaluates an expression, prints the error message if it fails, and carries on. With silent = TRUE it prints nothing; check the result with inherits(result, "try-error"):

r · try it yourself
results <- list()
for (input in list(10, "x", 4)) {
  r <- try(log(input), silent = TRUE)
  if (inherits(r, "try-error")) {
    cat("skipping bad input\n")
  } else {
    results[[length(results) + 1]] <- r
  }
}
round(unlist(results), 3)
skipping bad input
[1] 2.303 1.386

Warnings that should not interrupt

suppressWarnings() and suppressMessages() silence conditions you expect and don't care about. Use them sparingly; warnings usually mean something:

r · try it yourself
x <- c("1", "2", "three", "4")
nums <- suppressWarnings(as.numeric(x))
nums
sum(nums, na.rm = TRUE)
[1]  1  2 NA  4
[1] 7

Custom condition classes

stop() and warning() also accept a condition object. Giving it a class lets callers handle specific problems differently:

r · try it yourself
withdraw <- function(balance, amount) {
  if (amount > balance) {
    cond <- structure(
      class = c("insufficient_funds", "error", "condition"),
      list(message = sprintf("need %.2f more", amount - balance), call = NULL)
    )
    stop(cond)
  }
  balance - amount
}
tryCatch(withdraw(50, 80),
  insufficient_funds = function(e) cat("Declined:", conditionMessage(e), "\n"),
  error = function(e) cat("Other error\n"))
Declined: need 30.00 more

Test yourself

What happens when stop() is called and nothing handles it?

  1. A warning is printed and the code continues
  2. Execution stops with an error message
  3. It returns NA
  4. Nothing

When does the finally block of tryCatch() run?

  1. Only on errors
  2. Only on success
  3. Always
  4. Only on warnings

How do you get the text of a caught error e?

  1. e$text
  2. print(e)
  3. conditionMessage(e)
  4. message(e)