TryCatch不打印警告,除非警告包装在()中

时间:2019-03-11 22:34:38

标签: r try-catch

TryCatch不会打印警告,除非警告用括号括起来。

tryCatch(
  {
  print(wd)
},
error=function(e){
 (warning(sprintf('Watch out %s',e)))}
)

打印警告““小心打印(wd)中的错误:找不到对象'wd'\ n”

但是

tryCatch(
   {
 print(wd)
    },
    error=function(e){
     warning(sprintf('Watch out %s',e)) }
    )

没有。

知道为什么吗?我怎样才能解决这个问题?此示例是一个最小示例。我有一个更大的函数,它通过循环运行,如果有错误,我不一定要停止循环,但是我想查看警告。

1 个答案:

答案 0 :(得分:1)

对于您的循环,您可能想要使用messagecat,例如:

for (i in 1:2)
    tryCatch(print(wd),
             error = function(e) message(sprintf('Watch out %s',e)))
## Watch out Error in print(wd): object 'wd' not found
## 
## Watch out Error in print(wd): object 'wd' not found

要了解您的两个版本中发生了什么:

  • warning不打印任何内容。它发出警告, 处理程序可能会立即打印或安排稍后打印。

  • 如果处理程序未执行非本地控制权转移, 例如到tryCatch,然后?warning对此值进行说明 返回:

  

值:

The warning message as ‘character’ string, invisibly.
  • 如果表达式不可见地返回结果,则将其括在括号中 使结果可见。帮助文件经常使用成语

    (x <- foo(y))
    

    使分配结果可见并在顶层打印出来。

相关问题