Skip to content

Error trapping in R

6 messages · Duncan Murdoch, Rui Barradas, Robert Knight +1 more

#
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.

Bernard
Sent from my iPhone so please excuse the spelling!"
#
On 27/02/2019 3:55 p.m., Bernard Comcast wrote:
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)
                  someOtherFunction(y)
                })
   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
#
Hello,

You can trap errors with ?try or ?tryCatch.
Example:


result <- vector(mode = "list", length = 5)
for(i in 1:5){
   result[[i]] <- tryCatch(if(i == 3) stop("This is an error") else 2*i + 1,
            error = function(e) e)
}

result

for(i in seq_along(result)) {
   err <- inherits(result[[i]], "error")
   print(err)
}


Hope this helps,

Rui Barradas

?s 20:55 de 27/02/2019, Bernard Comcast escreveu:
#
Some use try blocks, like found in other languages.  Put the code you want to try inside the block.

https://www.robertknight.io/blog/try-blocks-in-r-for-error-handling/ contains a quick example.  The example doesn?t raise exceptions or anything, it just contains it for you so the script keeps going.  I like handling errors with if statements inside of try blocks.

Robert

  
  
#
Thanks

Bernard
Sent from my iPhone so please excuse the spelling!"
#
Thanks - the try() approach is exactly what I need.



Lion Bernard McGarvey

Director, Fort Myers Beach Lions Foundation, Inc.

Retired (Lilly Engineering Fellow).