What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

tryCatch() function in R

  • Jan 07, 2024
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abhisek Ganguly
tryCatch() function in R

Error handling is an essential aspect of R programming that guarantees the stability and reliability of your code. The tryCatch function in the R programming language makes this kind of error management possible. With the help of this function, you can handle errors with grace by having a way to run different code or send helpful messages when something goes amiss. In this article, we are going to learn about the different error-handling techniques in R using the tryCatch function.

What is the tryCatch function?

The tryCatch is a function in R designed specifically to handle Errors and manage Exceptions. The basic syntax of tryCatch goes as follows.

tryCatch(expr, error = function(e) default_handler, warning = function(w) warning_handler, finally = expression)

 

Here,

  • expr: The expression to be evaluated.
  • error: A function to handle errors.
  • warning: A function to handle warnings.
  • finally: A code block that is executed regardless of whether an error occurs or not.

Handling Errors

Errors are problems that stop code from running normally. These can include missing variables, problems with data types, and syntax errors. The tryCatch function's error argument lets you designate a unique function to handle errors.

result <- tryCatch({
  stop("This is a custom error.")
}, error = function(e) {
  cat("An error occurred: ", conditionMessage(e), "\n")
})

 

The custom error message in this case is "This is a custom error." The error function is triggered in the event of an error, which then displays a message and offers the chance for further error handling.

Handling Warnings

Warnings suggest that there may be problems with the code, but they do not necessarily stop it from running. The tryCatch function's warning argument lets you specify a unique function to handle warnings.

result <- tryCatch({
  warning("This is a custom warning.")
  42
}, warning = function(w) {
  cat("A warning occurred: ", conditionMessage(w), "\n")
})

 

In this example, the warning function is called to handle the custom warning message that has been generated. After the message is displayed in the event of a warning trigger, the code keeps running.

What is a Finally Block?

The finally block in tryCatch is optional and contains code that runs whether or not there is an error or warning. This block is helpful for data logging and resource cleanup, among other things.

result <- tryCatch({
  print("Executing the main code.")
}, finally = {
  print("This block always gets executed.")
})

 

In this example, the finally block ensures that its contained code is executed, regardless of the outcome of the main code.

Handling Errors in Loops with tryCatch

Let us now look at how to handle errors when working in loops in R.

1. tryCatch with For Loop

Errors must be carefully handled when using loops in R, especially when working with big datasets. A for loop can easily incorporate the tryCatch function to handle any errors that may occur while the loop is running.

for (i in 1:5) {
  result <- tryCatch({
    if (i == 3)
      stop("An error occurred on iteration 3.")
    else
      print(paste("Iteration", i))
  }, error = function(e) {
    cat("Error on iteration", i, ": ", conditionMessage(e), "\n")
  })
}

 

In this case, the third iteration of the loop purposefully causes an error. The tryCatch function guarantees that the loop persists in spite of the error, and it presents the error message and an option for further error handling.

 

2. tryCatch with Continue

In some situations, you might want to keep running the loop even after an error happens. Using the subsequent keyword in the tryCatch block will accomplish this.

for (i in 1:5) {
  result <- tryCatch({
    if (i == 3)
      stop("An error occurred on iteration 3.")
    else
      print(paste("Iteration", i))
  }, error = function(e) {
    cat("Error on iteration", i, ": ", conditionMessage(e), "\n")
    next
  })
}

 

In this example, the next keyword is used in the tryCatch block to continue to the next iteration of the loop when an error occurs. This ensures that the loop continues execution even if errors are encountered.

try Vs tryCatch

Although both the try and the tryCatch functions are used in R to handle errors, there are subtle differences among them. When handling errors is all that is required, you can use the simpler try function.  On the other hand, tryCatch provides more flexibility by allowing you to handle both errors and warnings, and it includes a finally block for code that must be executed regardless of errors or warnings.

1. Using try

In this, the try function is used to handle errors. If an error occurs, it returns an object of class "try-error," and you can extract information about the error using functions like conditionMessage.

result <- try({
  stop("This is a custom error.")
})

 

2. Using tryCatch

Here, errors and warnings are handled by the tryCatch function. It offers more precise control over the error-handling procedure by having distinct handlers for warnings and errors.

result <- tryCatch({
  warning("This is a custom warning.")
  stop("This is a custom error.")
}, error = function(e) {
  cat("An error occurred: ", conditionMessage(e), "\n")
}, warning = function(w) {
  cat("A warning occurred: ", conditionMessage(w), "\n")
})

 

Conclusion

In conclusion, writing solid and consistent code requires an understanding of R's flexible `tryCatch` function for error handling. This thorough article has shed light on its syntax and uses, showcasing how well it handles errors and warnings—especially when it comes to for loops. We compared the differences between try and tryCatch, highlighting the latter's flexibility and additional features, such as the else clause that offers more exact control over code execution. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abhisek Ganguly
Passionate machine learning enthusiast with a deep love for computer science, dedicated to pushing the boundaries of AI through academic research and sharing knowledge through teaching.