ZetCode

R error handling

last modified November 19, 2026

An error stops a script, a warning records a problem and lets the computation continue, and a message writes a note to the console. R implements all three as conditions: objects that carry a message, a call, and a class, and that travel up the call stack until a handler catches them. This article covers stop, warning, message, try, tryCatch, withCallingHandlers, custom condition classes, and cleanup with on.exit. The examples use R 4.5.2.

Messages, warnings, and errors

message writes a note to standard error, warning records a warning and lets the function return, and stop signals an error that unwinds the call stack. All three accept a condition object, but the common form is a character string that R wraps in a simpleMessage, simpleWarning, or simpleError. The call. argument controls whether the message includes the call that produced it.

signals.R
check_age <- function(age) {
  if (!is.numeric(age)) {
    stop("age must be numeric", call. = FALSE)
  }
  if (age < 0) {
    warning("age is negative", call. = FALSE)
  }
  message("accepted age ", age)
  age
}
negative <- check_age(-5)
cat("negative value:", negative, "\n")
check_age("old")

The first call passes a negative number. warning records the problem, message writes the note, and the function still returns -5. R prints Warning message: after the top-level call finishes, which is why the warning appears before the cat line rather than immediately after the warning call. The second call passes a string, so stop signals an error. Nothing catches it, so the script ends with Execution halted. The next section shows how try turns that failure into an object that the script can inspect.

$ Rscript signals.R
accepted age -5
Warning message:
age is negative 
negative value: -5 
Error: age must be numeric
Execution halted

Catching errors with try

try runs an expression and returns its value when the expression succeeds. When the expression signals an error, try prints the message and returns a character string with class try-error. The silent argument suppresses the print, which is useful when the caller will report the failure itself. try is convenient at the top level; it does not give the handler access to the condition beyond the text.

try-errors.R
parse_number <- function(text) {
  value <- suppressWarnings(as.numeric(text))
  if (is.na(value)) {
    stop("not a number: ", text, call. = FALSE)
  }
  value
}
first <- try(parse_number("42"))
second <- try(parse_number("forty-two"))
cat("first:", first, "\n")
cat("second class:", class(second), "\n")

as.numeric would warn about the coercion of "forty-two", so suppressWarnings removes that noise and the function reports the problem with its own message. The first try returns the number 42. The second prints the error and returns a try-error object, and the script continues to the final cat. Without try, the error would end the script with Execution halted.

$ Rscript try-errors.R
Error : not a number: forty-two
first: 42 
second class: try-error 

Handling errors with tryCatch

tryCatch associates handler functions with condition classes. When a condition is signalled, R looks for the first handler whose name matches the condition class and calls it; the value of the handler becomes the value of the tryCatch call. A finally expression runs on every path, whether the body succeeded, signalled a condition, or exited through return. This is the general tool for recovering from an error and for releasing resources.

trycatch.R
divide <- function(a, b) {
  tryCatch(
    {
      if (b == 0) {
        stop("division by zero", call. = FALSE)
      }
      a / b
    },
    error = function(e) {
      cat("handled:", conditionMessage(e), "\n")
      NA_real_
    },
    finally = cat("division attempted\n")
  )
}
cat("10 / 4 =", divide(10, 4), "\n")
cat("10 / 0 =", divide(10, 0), "\n")

The first call divides normally and still runs the finally expression, so division attempted appears before the result. The second call signals an error, the error handler prints the message and returns NA_real_, and finally runs again. The handler replaces the failed expression, which is why the outer cat can print 10 / 0 = NA instead of stopping. The finally block is the right place for a cleanup step that must run on both paths.

$ Rscript trycatch.R
division attempted
10 / 4 = 2.5 
handled: division by zero 
division attempted
10 / 0 = NA 

Turning warnings into errors

The warn option controls what R does with a warning. warn = 0 stores warnings and prints them after the top-level call, warn = 1 prints each warning as it happens, and warn = 2 converts every warning into an error. The last setting is useful in a script that must not continue with a doubtful result. Save the old options first and restore them afterwards.

warn_option.R
old <- options(warn = 2)
result <- try(sqrt(-1), silent = TRUE)
cat("class:", class(result), "\n")
cat("message:", conditionMessage(attr(result, "condition")), "\n")
options(old)
cat("warn restored:", getOption("warn"), "\n")

sqrt(-1) normally warns that NaNs were produced and returns NaN. With warn = 2 the warning becomes an error, so try catches it and the condition message records both facts: (converted from warning) NaNs produced. Restoring the old options returns the setting to zero, the default in a fresh session. Changing a global option affects every function that runs afterwards, so the restore belongs in the same block, ideally guarded with on.exit in a function.

$ Rscript warn_option.R
class: try-error 
message: (converted from warning) NaNs produced 
warn restored: 0 

Intercepting warnings

withCallingHandlers installs a handler that runs at the point where the condition is signalled, without unwinding the stack. The computation continues after the handler returns, unless the handler transfers control by invoking a restart. Warnings establish a muffleWarning restart, and calling invokeRestart("muffleWarning") suppresses the default warning output. This is how a program can log a warning and keep the result.

catch-warnings.R
log_values <- function(x) {
  withCallingHandlers(
    log(x),
    warning = function(w) {
      cat("warning:", conditionMessage(w), "\n")
      invokeRestart("muffleWarning")
    }
  )
}
values <- log_values(c(1, -1, 4))
cat("result:", values, "\n")

log(-1) produces NaN and signals a warning. The handler prints the message and muffles the warning, so R does not print its own warning line. The computation still finishes and returns a vector with zero, NaN, and the logarithm of four. Replacing withCallingHandlers with tryCatch would abort the log call at the first warning and lose the remaining values, which is the difference between inspecting a condition and unwinding to a handler.

$ Rscript catch-warnings.R
warning: NaNs produced 
result: 0 NaN 1.386294 

Custom conditions

A condition is an object with a class vector and at least a message and a call element. A custom class lets a handler catch one kind of failure while leaving other errors alone, and extra list elements can carry data that the handler needs. The class vector must include error and condition when the object is passed to stop, so that ordinary error handling still recognises it.

conditions.R
empty_input <- function(field) {
  structure(
    class = c("empty_input", "error", "condition"),
    list(message = paste(field, "is empty"), call = NULL, field = field)
  )
}
average <- function(x, field = "x") {
  if (length(x) == 0) {
    stop(empty_input(field))
  }
  mean(x)
}
report <- function(x, field) {
  tryCatch(
    average(x, field),
    empty_input = function(e) {
      cat("custom handler for", e$field, ":", conditionMessage(e), "\n")
      NA_real_
    }
  )
}
cat("average:", report(c(2, 4, 6), "scores"), "\n")
cat("empty:", report(numeric(0), "scores"), "\n")

The first call returns the mean, four. The second signals an empty_input condition, and tryCatch selects the handler named after that class before it considers the generic error handler. The handler reads e$field and returns NA_real_, so the script continues. The message is built once, in the constructor, which keeps the text consistent wherever the condition is raised. A caller that only wants to catch ordinary errors can omit the custom handler, and the condition still behaves like an error.

$ Rscript conditions.R
average: 4 
custom handler for scores : scores is empty 
empty: NA 

Cleaning up with on.exit

on.exit registers an expression that runs when the current function exits. The expression runs on a normal return and on an error, which makes it the right place to close a connection, delete a temporary file, or restore an option. With add = TRUE the new expression is appended to the list; without it, a later on.exit call replaces the earlier one. A function can register several cleanup steps and they run in the order they were added.

onexit.R
path <- tempfile(fileext = ".txt")
process <- function(path, fail = FALSE) {
  writeLines(c("alpha", "beta"), path)
  on.exit(unlink(path), add = TRUE)
  if (fail) {
    stop("processing failed", call. = FALSE)
  }
  readLines(path)
}
cat("lines:", length(process(path)), "\n")
cat("exists after success:", file.exists(path), "\n")
failed <- try(process(path, fail = TRUE), silent = TRUE)
cat("failed class:", class(failed), "\n")
cat("exists after error:", file.exists(path), "\n")

The first call writes two lines, reads them back, and removes the file on the way out. The second call fails before reading, but on.exit still removes the file. Both checks report FALSE, so the temporary file does not survive either path. The cleanup expression captures path from the function environment, so it removes the same file that the body created. Without on.exit, the error path would leave the file behind.

$ Rscript onexit.R
lines: 2 
exists after success: FALSE 
failed class: try-error 
exists after error: FALSE 

A complete example

The final script parses a small batch of comma-separated records. Each record is handled in its own tryCatch, so one bad line does not stop the others. The good rows are collected in a list and combined with rbind, while the error messages go into a character vector. The superassignment <<- updates errors in the enclosing function, because the handler runs in its own environment.

batch.R
parse_record <- function(entry) {
  parts <- strsplit(entry, ",")[[1]]
  if (length(parts) != 3) {
    stop("expected 3 fields, got ", length(parts), call. = FALSE)
  }
  value <- suppressWarnings(as.numeric(parts[3]))
  if (is.na(value)) {
    stop("bad value: ", parts[3], call. = FALSE)
  }
  data.frame(name = parts[1], city = parts[2], value = value)
}
process <- function(entries) {
  good <- list()
  errors <- character()
  for (entry in entries) {
    record <- tryCatch(
      parse_record(entry),
      error = function(e) {
        errors <<- c(errors, conditionMessage(e))
        NULL
      }
    )
    if (!is.null(record)) {
      good[[length(good) + 1]] <- record
    }
  }
  list(data = do.call(rbind, good), errors = errors)
}
data_lines <- c("Ada,Bratislava,91", "Grace,Kosice,88",
                "Alan,Zilina", "Bob,Nitra,high")
result <- process(data_lines)
print(result$data)
cat("errors:", length(result$errors), "\n")
cat(result$errors, sep = "\n")

Two records have all three fields and a numeric value, so they become rows of the result. Alan has only two fields and Bob has a non-numeric value; each failure is caught, recorded, and skipped. The final report keeps the good data and the reasons for the rejected lines together, which is usually more useful than stopping at the first bad record. If no line is valid, do.call(rbind, good) returns NULL, so a production script would check for that case before returning the data frame.

$ Rscript batch.R
   name       city value
1   Ada Bratislava    91
2 Grace     Kosice    88
errors: 2 
expected 3 fields, got 2
bad value: high

Next steps

The debugging article shows how to find the place where an error was raised and how to inspect the call stack before writing a handler. The functions article explains the evaluation rules behind on.exit and lazy arguments, and the missing values article covers NA and the tests that belong in a validation function. The data I/O article shows how to read a full file when the records come from disk rather than from a vector.

Source

R manual: Conditions, tryCatch, and withCallingHandlers

R manual: on.exit

Advanced R: Conditions

In this article we have signalled messages, warnings, and errors, caught them with try and tryCatch, intercepted warnings with withCallingHandlers, and defined a condition class of our own. on.exit cleaned up a temporary file on both the successful and the failing path, and the batch example turned per-record failures into a report instead of a stopped script. The debugging article shows how to find where those conditions come from and which call produced them.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.