2017-07-18 74 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 
相关问题