tryCatch() Function in R

tryCatch() function in R is used for handling errors. The function returns the expression value or generates a custom message when an error or warning occurs. This guide explains how to use the tryCatch() function in R.

Syntax

tryCatch(expr, ..., finally)
tryCatch({
expr
}, error = function(e) {
code for handling error
}, warning = function(w) {
code for handling warning
}, finally = {
clean-up code
}

Arguments

  • expr = expression to be evaluated.
  • error = error handling function. It is called if an error occurs when evaluating the expression.
  • warning = warning handling function. it is called if a warning occurs when evaluating the expression.
  • finally = function to run after the execution of the tryCatch function. This argument is optional.

Example 1

In this example, we evaluate an expression that causes an error. Then, we will use the tryCatch() function to handle the error.

# creating an error by dividing a character by an integer
x/12

Output

Error in x/12: non-numeric argument to binary operator
#using the tryCatch() function to handle the error
tryCatch({
expr = x/12 #expression
}, error = function(e) {
print("There is an error!") #printing a message when prompted with an error
}, finally ={
print("code executed") #printing a message after code execution
})

Output

[1] "There is an error!"
[1] "code executed"

Example 2

In this example, we evaluate an expression that will cause a warning. Then, we will use the tryCatch() function to handle the warning.

# taking a square root of a negative number generates a warning
sqrt(-1)

Output

[1] NaN
Warning message:
In sqrt(-1) : NaNs produced
#using the tryCatch() function to handle the warning
tryCatch({
expr = sqrt(-1) #expression
}, warning = function(w) {
print("There is a warning!") #printing a message when prompted with a warning
}, finally ={
print("code executed") #printing a message after code execution
})

Output

[1] "There is a warning!"
[1] "code executed"

Leave a Comment