How to recover error in R?

I will catch the error using tryCatch and try to handle the error. However, how can I reprogram the error if I cannot handle the error locally (i.e., delegate the error handlers of the parent functions above in the call stack)?

I tried using signalCondition , but instead of seeing a repeated error, all I see is NULL :

 > error.can.be.handled <- function(e) F > > foo <- function() stop("foo stop!") > tryCatch(foo(), + error = function(e) { + if (error.can.be.handled(e)) { + # handle error + } + else + signalCondition(e) # Rethrow error + } + ) NULL # I expected to see 'Error in foo() : foo stop!' here 

What will go wrong?

+8
r try-catch error-handling
source share
3 answers
 tryCatch(stop("oops"), error=function(e) stop(e)) 

will re-signal the stop condition, although the context has been lost

 > tryCatch(stop("oops"), error=function(e) stop(e)) Error in doTryCatch(return(expr), name, parentenv, handler) : oops > traceback() 5: stop(e) 4: value[[3L]](cond) 3: tryCatchOne(expr, names, parentenv, handlers[[1L]]) 2: tryCatchList(expr, classes, parentenv, handlers) 1: tryCatch(stop("oops"), error = function(e) stop(e)) > tryCatch(stop("oops")) Error in tryCatchList(expr, classes, parentenv, handlers) : oops > traceback() 3: stop("oops") 2: tryCatchList(expr, classes, parentenv, handlers) 1: tryCatch(stop("oops")) 

The return of only e , as @tonytonov suggests, indicates that a condition has occurred, but not that an error has occurred.

+7
source share

No need for signalCondition ():

 tryCatch(foo(), error = function(e) { if (error.can.be.handled(e)) { # handle error } else e # Rethrow error } ) <simpleError in foo(): foo stop!> 
0
source share

A workaround you can use to avoid having to catch and rethrow the error. Basically, use the success flag with the on.exit handler to run the code block only if the code fails:

 foo <- function() stop("foo stop!") runFoo <- function() { success <- FALSE on.exit({ if (!success) { ## Handle failure } }) result <- foo() success <- TRUE result } runFoo() 

The main disadvantage of this approach is that, although you know that an error occurred (since success never set to TRUE), you do not get access to the error object itself, so you will need to use some other method to determine if whether you handle the error or not.

The runFoo wrapper runFoo necessary because the on.exit expression on.exit executed when the current function exits, so it needs to be run inside the function. If the code you are writing is already inside the function, you do not need to use this shell.

0
source share

All Articles