How to Use the tryCatch Function for Condition Handling in R

Jinku Hu Feb 02, 2024
How to Use the tryCatch Function for Condition Handling in R

This article will demonstrate multiple methods of using the tryCatch function for condition handling in R.

Use tryCatch to Handle Error Conditions in R

Three types of built-in conditions are provided in R language, which can be thrown as exceptions from the code. Conventionally, the most severe ones are called errors, which usually terminate the function or execution is stopped. Then, there are warnings, which indicate if some error occurs during the function execution, but it’s able to handle the issue partially. Finally, we have messages that are used to inform about some mild issues to the user. These three conditions have corresponding functions named stop, warning and message, which can be invoked to raise the given condition.

f1 <- function(x) {
  cat("log(", x, ") = ", (log(x)))
}

f1(10)

Output:

log( 10 ) = [1] 2.302585

For example, the previous code defines a function named f1 that takes a single argument x and prints the log(x) result with some additional formatting. Notice that if the user passes a non-numeric argument to the f1 function, it throws an error. We can handle this error by registering the handler with the tryCatch function.

f1 <- function(x) {
  cat("log(", x, ") = ", (log(x)))
}

f1("f")

Output:

Error in log(x) : non-numeric argument to mathematical function

Note that registering the handler means that we override the default code for this error with the user-supplied one. The following example demonstrates how the default error message is replaced with the custom output string. Meanwhile, the following function behaves normally if the error condition is not raised.

f1 <- function(x) {
  tryCatch(
    error = function(cnd) "The custom output that we need to print",
    cat("log(", x, ") = ", (log(x)))
  )
}

f1("f")

Output:

[1] "The custom output that we need to print"

The common usage for the tryCatch function is to implement a code block that needs to execute when the error condition is thrown. We specify the code block that executes when an error is raised in the curly braces after the error = function(cnd) line. The following lines after the error code block are usually run when the handler is active.

f1 <- function(x) {
  tryCatch(
    error = function(cnd) {
      print("hello")
      log(10)
    },
    cat("log(", x, ") = ", (log(x)))
  )
}

f1("x")

Output:

[1] "hello"
[1] 2.302585
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook