Handling Errors Gracefully

May 27, 2011
By

(This article was first published on Software for Exploratory Data Analysis and Statistical Modelling, and kindly contributed to R-bloggers)

In R functions sometimes produces warnings or errors. In the case of errors execution of a function or a series of commands can get halted when an error occurs, which can in some cases be frustrating especially if we want to continue our calculations.

There are various functions available in R for dealing with errors and in this post we will consider some basic examples of how to make use of the try function.

To illustrate how to use try let’s look at what happens if we run code to print out a non-existent object in our workspace:

> print(d) Error in print(d) : object 'd' not found

Now if we try to run another command at the same time to print out a string then we would get the following output:

> print(d); print("Hi") Error in print(d) : object 'd' not found

Here execution of the code halts after the first command fails and generates an error. We can modify this code to call the try function with the print statement:

> try(print(d)); print("Hi") Error in print(d) : object 'd' not found [1] "Hi"

The second statement is now evaluated even though an error occurs at the first statement. This is a trivial example and in other situations we might consider using the tryCatch function which has various arguments in addition to the expression to evaluate including a function to be called when an error occurs.