Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rethrow an error in R?

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?

like image 793
mchen Avatar asked Dec 25 '13 07:12

mchen


People also ask

How do you catch an error in R?

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

How do I do an Ignore error in R?

The simplest way of handling conditions in R is to simply ignore them: Ignore errors with try() . Ignore warnings with suppressWarnings() .


1 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"))

Returning just e as @tonytonov suggests does signal that a condition has occurred, but not that an error has occurred.

like image 186
Martin Morgan Avatar answered Oct 08 '22 04:10

Martin Morgan