๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Error Handling

Error handling is a way to catch an error before it stops a script. A handler decides what happens in place of the halt.

Catching an error

tryCatch runs the check_age call inside it. The handler gives back the text caught it and the print shows that text.

check_age <- function(age) {
  if (age < 18) {
    stop("too young")
  }
  return("old enough")
}
result <- tryCatch(check_age(15), error = function(e) "caught it")
print(result)

Reading the error text

The handler takes in the error from check_age. conditionMessage reads the text too young out of that error.

check_age <- function(age) {
  if (age < 18) {
    stop("too young")
  }
  return("old enough")
}
msg <- tryCatch(check_age(15), error = function(e) conditionMessage(e))
print(msg)

Example

check_age <- function(age) {
  if (age < 18) {
    stop("too young")
  }
  return("old enough")
}
result <- tryCatch(check_age(21), error = function(e) "caught it")
print(result)

Key points

  • tryCatch runs code and watches for an error.
  • The handler is a function of one argument.
  • The handler argument holds the error itself.
  • conditionMessage() reads the text of an error.
  • tryCatch gives back the value of the code when no error occurs.
  • Handling suits code that may fail on some inputs.

In this example, the age passes the check inside tryCatch. No error occurs and tryCatch gives back the normal result of the call.

Note

A caught error does not stop the script.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does tryCatch give back when the code runs with no error?