Using R — Easier Error Handling with try()

This entry is part 6 of 20 in the series Using R

In a previous post we looked at error handling in R with the tryCatch() function and how this could be used to write Java style try-catch-finally blocks. This time we’ll look at what can be done with the try() function and how we can easily process warning and error messages to take appropriate action when something goes wrong.

The try() function is really just a simplified interface to tryCatch(). To see how try() calls tryCatch() you can examine the guts of the try() function by typing try [without parens] at the R prompt but you may not like what you see. For those of us outside the R core development team, this is not a good place to start. The ?try documentation is much better and has a useful example showing how try() can be used to generate simulated results, ignoring those that generated errors. But this documentation doesn’t address the kind of error handling one needs for ‘business logic’ where different actions are taken depending on the kind of error issued.

For this post, we will more generally explore how try() can be used and how warning and error messages can be processed using geterrmessage() and grepl(). The important things to remember about these functions are:

  • try() only ignores warnings, not errors
  • options(warn=2) turns warnings into errors
  • geterrmessage() returns the character string associated with the last error
  • grepl(pattern, string) returns TRUE if ‘pattern’ if found within ‘string’, FALSE otherwise

With just these functions we have everything we need to write very simple constructs that can evaluate a function and handle both errors and warnings. The test script at the end of this post demonstrates how messages and errors can be generated within a function and then trapped and processed by a calling function, potentially generating new errors that could be passed upstream. Just copy and paste the script at the end, make it executable and try it out with the these shell commands:

And here is the script.

Series NavigationUsing R — Package Installation ProblemsUsing R — Calling C Code ‘Hello World!’
This entry was posted in R and tagged , . Bookmark the permalink.

4 Responses to Using R — Easier Error Handling with try()

  1. Thanks for finally writing about > Using R – Easier Error Handling with try() | Working With Data < Liked it!

  2. Pingback: try « Chemiomet[R]ia

  3. Gu Mi says:


    I like your posts on R programing tips. Thank you for the helpful posts! Here is a minor issue in the codes: I think in
    warning(“custom warning message”, .call=FALSE)
    the last argument should be call. = FALSE. Maybe it’s due to updates for these warning/error-handling functions.