I'll catch an error using tryCatch
, and attempt to handle the error. However, how can I rethrow the error if I cannot handle the error locally (i.e. delegate to error handlers of parent functions higher up in the call stack)?
I tried using signalCondition
but instead of seeing the rethrown 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's going wrong?
tryCatch() in R The tryCatch() function in R evaluates an expression with the possibility to catch exceptions. The class of the exception thrown by a standard stop() call is try-error. The tryCatch() function allows the users to handle errors. With it, you can do things like: if(error), then(do this).
The simplest way of handling conditions in R is to simply ignore them: Ignore errors with try() . Ignore warnings with suppressWarnings() .
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"))
Returning just e
as @tonytonov suggests does signal that a condition has occurred, but not that an error has occurred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With