Site icon R-bloggers

Handling Errors Gracefully

[This article was first published on Software for Exploratory Data Analysis and Statistical Modelling, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

To leave a comment for the author, please follow the link and comment on their blog: Software for Exploratory Data Analysis and Statistical Modelling.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.