为什么withCallingHandlers仍然抛出错误?

时间:2019-09-19 17:59:25

标签: r

some_f <- function() {
  stop("Error")
}

t2 <- withCallingHandlers({some_f()},
         error=function(err){print("got here")},
         warning=function(warn){return(NULL)})

输出:

[1] "got here"
 Error in some_f() : Error 
3. stop("Error") 
2. some_f() 
1. withCallingHandlers({
      some_f()
   }, error = function(err) {
      print("easldfa") ... 

激活了错误功能,因为已打印出“此处获得”。但是它仍然抛出错误。它不应该那样做。

1 个答案:

答案 0 :(得分:0)

您正在将withCallingHandlerstryCatch混合在一起。当您使用withCallingHandlers时,将调用您的处理程序,然后调用之前建立的其他任何处理程序,即在您的示例中为错误条件的默认处理程序。

要获得您期望的行为,请使用类似以下的内容:

> some_f <- function() {
+   stop("Error")
+ }
> 
> t2 <- tryCatch({some_f()},
+          error=function(err){print("got here")},
+          warning=function(warn){return(NULL)})
[1] "got here"

这也会将t2设置为"got here",因为这是print()函数的结果。您可以将其他值作为该错误处理程序的返回值,例如

> t2 <- tryCatch({some_f()},
+          error=function(err){print("got here"); 123},
+          warning=function(warn){return(NULL)})
[1] "got here"
> t2
[1] 123