如何在R中重新抛出错误?

mch*_*hen 10 error-handling r try-catch

我将使用错误tryCatch并尝试处理错误.但是,如果我无法在本地处理错误(即委托给调用堆栈中较高位置的父函数的错误处理程序),如何重新抛出错误?

我尝试使用signalCondition但不是看到重新抛出的错误,我只看到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
Run Code Online (Sandbox Code Playgroud)

出了什么问题?

Mar*_*gan 10

tryCatch(stop("oops"), error=function(e) stop(e))
Run Code Online (Sandbox Code Playgroud)

虽然背景已经丢失,但会重新发出停止状态的信号

> 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"))
Run Code Online (Sandbox Code Playgroud)

e正如@tonytonov建议的那样返回确实表明已经发生了一个条件,但并没有发生错误.