2017-07-18 30 views
3

檢查下面的例子:爲什麼tryCatch在被要求生產時不會返回警告?

library(testthat) 
expect_warning(tryCatch(stop("Error!"), error = function(e) warning(e))) 
## Error: tryCatch(stop("Error!"), error = function(e) warning(e)) showed 0 warnings 
## In addition: Warning message: 
## In doTryCatch(return(expr), name, parentenv, handler) : Error! 

爲什麼testthat說,沒有警告?

使用withWarnings function discussed in here也沒有顯示警告信號。爲什麼tryCatch如果要求它不會產生警告?

回答

2

您創建了嵌套調用doTryCatchwithCallingHandlers。問題是e不是一個字符,而是一個simpleError對象(它包含對doTryCatch的另一個調用)。以下有些作品,但顯示了警告的實際上下文:

tryCatch(stop("Error!"), error = function(e) warning(e[[1]])) 
#Warning message: 
#In value[[3L]](cond) : Error! 
library(testthat) 
expect_warning(tryCatch(stop("Error!"), error = function(e) warning(e[[1]]))) 
#no further output 
相關問題