[R] Error trapping in R

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Wed Feb 27 22:05:47 CET 2019

On 27/02/2019 3:55 p.m., Bernard Comcast wrote:
> What is the recommended way to trap errors in R? My main need is to be able to trap an error and then skip a section of code if an error has occurred. In VB for Excel I used the “On Error goto  .....” construct to do this.

The recommended way is to use tryCatch() around the expression you're 
evaluating.  A simpler, less flexible alternative is try().  The Excel 
version sounds a bit more like try().  You'd use it like this:

   value <- try({ x <- 1
                  y <- someFunction(x)
   if (inherits(value, "try-error")) {
     cat ("something went wrong.  There's information in value about 
what happened.")
   } else {
     cat ("value is fine, there was no error.")

Duncan Murdoch

More information about the R-help mailing list