tryCatch() Function in R: How to Handle Errors and Exceptions

When you are writing big programs, sometimes something goes wrong with your R code. What do you do if the program stops unexpectedly? What tools do you have to address the problem? This is where the tryCatch() function will help you. Debugging is the art and science of fixing unexpected problems in your code.

Error Handling is a process in which we deal with an unwanted or anomalous error that may cause unnatural termination of the program during its execution.

The basic functions that one can use for error handling in R are the following.

  1. stop(…): The stop() function halts the evaluation of the current statement and generates a message argument. The control is returned to the top-level.
  2. waiting(…): Its evaluation depends on the value of the error option warn. If the value of the warning is negative, then it is ignored. In case the value is 0 (zero), they are stored and printed only after the top-level function completes its execution. If the value is 1 (one), then it is printed as soon as it has been encountered, while if the value is 2 (two), then immediately, the generated warning is converted into an error.
  3. tryCatch(…): The tryCatch() function helps evaluate the code and assign the exceptions.

In this article, we will see how the tryCatch() function works.

tryCatch() in R

The tryCatch() function in R evaluates an expression with the possibility to catch exceptions. The class of the exception thrown by a standard stop() call is try-error. The tryCatch() function allows the users to handle errors. With it, you can do things like: if(error), then(do this).

In tryCatch(), there are two ‘conditions’ that can be handled: ‘warnings’ and ‘errors’. The important thing to understand when writing each block of code is the state of execution and the scope.

Syntax

result = tryCatch({
 expression
}, warning = function(w) {
 warning-handler-code
}, error = function(e) {
 error-handler-code
}, finally = {
 cleanup-code
}

Parameters

expression: The expression to be evaluated.
…: A catch list of named expressions. The expression with the same name as the class of the Exception thrown when evaluating an expression.
finally: An expression that is guaranteed to be called even if the expression generates an exception.
envir: The environment in which the caught expression is to be evaluated.

Example

Let’s try to find the log of character value in R and analyze the output.

data <- log("ABC")
data

Output

Error in log("ABC") : non-numeric argument to mathematical function
Execution halted

We can see that we got an error saying: non-numeric argument to a mathematical function execution halted.

Now maybe you would want something to happen when such an error happens. You can handle this kind of error using the tryCatch() function.

tryCatch(log("ABC"),
 error = function(e)
 print("You can't calculate the log of a character"))

Output

[1] "You can't calculate the log of a character"

The tryCatch() function returns the value associated with executing the expression unless there’s an error or a warning.

In some cases, the specific return values (see a return(NA) above) can be specified by supplying a respective handler function (see arguments error and warning in ?tryCatch).

Second Example of tryCatch() in R

Write the following code inside the R file.

arg <- 0

div <- function(num, a) {
 if (a == "warning") {
 val <- "It is a warning"
 warning("warning message")
 }
 else if (a == "error") {
 val <- "It is an error"
 stop("error!!")
 }
 else {
 val <- num / as.numeric(a)
 }
 return(val)
}

vl <- tryCatch({

 b <- 1
 e <- div(b, arg)

},
warning = function(warn) {
 print(paste("MY WARNING: ", warn))
},
error = function(err) {
 print(paste("MY ERROR: ", err))
},
finally = function(f) {
 print(paste("e: ", e))
})
print(paste("Output: ", vl))

Output

[1] "Output: Inf"

In this example, you can see that if we are dividing any value with 0, then it will return an Infinity or Inf in our case.

That is it for tryCatch() function in R language.

Leave a Comment