Error Handling in R

Sometimes errors may need to be forced, like when running experiments, testing various input parameters, etc. It becomes imperative to take alternative routes when errors occur so as to smoothly handle them. This post shows you all about error handling features in R

Easiest way: show.error.messages=F

There are ways to graciously handle error messages in R. The first and the most simple way is to tell R not to display any error messages, no matter how brutal it is. Try the following code in your R console, you will notice that you R does not display error messages right after turn error messages OFF. You can turn it back ON by setting this to TRUE again.

options(show.error.messages=F) # turn off
1 <- 1 # cause of error, but no error messages printed out!
options(show.error.messages=T) # turn it back on
1 <- 1
Error in 1 <- 1 : invalid (do_set) left-hand side to assignment

Lets try()

Though you have turned off displaying error messages above, you have not actually ‘handled’ it. You can say the error messages are ‘handled’ when you are able to perform some alternative measures in the event errors happen. In the code below, we have a simple for-loop iterating 10 times, where the counter ‘i’ takes the values 1 – 10. You are going to intentionally trigger an error and see what value the counter i holds at the end of the loop. If the loop had run in full successfully, i should hold the value 10.
for (i in c(1:10)) {
1 <- 1 # trigger the error
print (i) # i equals 1. Never ran through full loop

Without the error handling feature, the loop is broken as soon as an error is encountered and the rest of the iterations are abruptly stopped. However, there are scenarios where you will want the loop to continue even if an error is encountered. This can be easily done by passing the error-prone function into a try() function. In this case, the loop continues to iterate even after it encounters an error.
for (i in c (1:10)) {
triedOut <- try(1 <- 1) # try an error creating statement.
print (i) # i equals 10. Runs through full loop

Further more, you can find out if an error did really occur by checking for the class of stored ‘triedOut‘ variable.
If an error really did occur, it will have the class named “try-error”. You can get creative by having a condition that checks the class of this variable, and take alternative measures.
class(triedOut) # "try-error"

You can even pass multiple lines of code within try() by enclosing them in a pair of curly braces {}. We are almost set with error handling. But your knowledge of handling errors is not complete without knowing about tryCatch().

Catch them all with: tryCatch()

tryCatch() lets you handle errors in a more structured fashion, encompassing the actual error-handling part (as a ‘error’ function) in one of its argument. Time to introduce the tryCatch().

How to use tryCatch() ?

The trycatch() function has three blocks written within curly braces as seen in code below. The first curly brace block takes in the statements, just like the try() function we saw earlier. Like try(), it can now take multiple lines of code within the 1st set of curly brackets.
If an error was encountered in ANY of the statements in the first block, then the error message generated will be stored in a ‘err’ variable (see code below) that the error handling function (called ‘error’) uses. You can choose to print out this error message, do some alternative calculation or whatever you want. You can also even perform a completely different set of logics within this function that doesn’t involve the error message. Its really upto you.
The last set of curly braces called ‘finally’ is meant to be executed regardless of whether an error did or did not occur. You may choose to ignore adding any statements to this part altogether.
Here is an example.
tryCatch ({1 <- 1; print ("Lets create an error")}, # First block
error=function(err){print (err); print ("Error Line")}, # Optional Second Block
finally = {print ("finally print this")}) # Optional Third Block

# [1] "Lets create an error"
# [1] "Error Line"
# [1] "finally print this"

Explanations: What happened up there?

Within the first block, we intentionally issued a statement that would trigger an error (1 <- 1). R did not print out the error message right away but printed only the line “Lets create an error” as expected. We could have added as many lines of code if we want within this first set of curly braces which we call ‘First block’. This is the only mandatory argument for tryCatch() and the two blocks that follows are only optional.

In the second block, we define a function that takes the ‘error’ itself as the argument. It doesn’t matter what name we give to this function, but if we did, that function argument will hold the ‘error’ (if created in the first block) within that block.

The third block, can optionally perform some concluding steps if you wish. Here in this case we have printed out “finally print this” just so you know how it behaves.

If you like us, please tell your friends.Share on LinkedInShare on Google+Share on RedditTweet about this on TwitterShare on Facebook