嵌套的tryCatch没有捕获错误?

时间:2012-04-19 05:58:36

标签: r try-catch raise

我有一个功能:

buggy <- function(...) {
    tryCatch({
        itWorked <- FALSE
        stop("I don't like green eggs and ham!")
        itWorked <- TRUE
    }, finally = {
        if ( itWorked )
            return("I do, Sam I am")
        else
            return("I do not like them, Sam I am!")
    })
}

基本上,buggy尝试进行一些可能成功或未成功的计算(由itWorked确定。finally子句确保即使计算不起作用,返回一些东西(在这种情况下,"I do not like them, Sam I am!")。

按预期工作:

> buggy()
Error in tryCatchList(expr, classes, parentenv, handlers) : 
  I don't like green eggs and ham!
[1] "I do not like them, Sam I am!"

现在我想听一下buggy()中的错误:

tryCatch( buggy(), 
          error=function(e) message('too bad! there was an error') )

然而buggy中的错误未能引发周围tryCatch的错误:

> tryCatch( buggy(), 
+           error=function(e) message('too bad! there was an error') )
[1] "I do not like them, Sam I am!"

我希望这会说:

'too bad! there was an error'
[1] "I do not like them, Sam I am!"

谁能告诉我为什么这不起作用?我是否需要在buggy内“提出”错误?

1 个答案:

答案 0 :(得分:2)

外部tryCatch()没有为您提供完全error参数中存储的消息,原因与以下调用不相同:

tryCatch("I do not like them, Sam I am!",
    error=function(e) message('too bad! there was an error') )
# [1] "I do not like them, Sam I am!"

只有在error返回错误时才会调用buggy()参数中两行的消息。但相反(感谢tryCatch()内部的工作),buggy()只返回一个字符向量,而tryCatch()没有任何东西可以“捕获”:

value <- buggy()
value
# [1] "I do not like them, Sam I am!"

# And, to belabor the point:
identical(buggy(), "I do not like them, Sam I am!")  
# [1] TRUE