【问题标题】:tryCatch: Why is warning handled as error?tryCatch:为什么将警告作为错误处理?
【发布时间】:2014-10-28 19:45:22
【问题描述】:

为什么下面的代码没有返回2,而是将警告作为错误处理?

tryCatch({
  1+1
  warning("test")
  return(2)
}, error=function(e){
  print("error")
}, finally = {})

[1] "error"
Warning message:
In doTryCatch(return(expr), name, parentenv, handler) : test

如何只处理错误而忽略警告?

【问题讨论】:

  • 不要使用return。只需2 就足够了。
  • @jbaums 在意识到我的愚蠢之后,我意识到您的建议完全解决了问题,因为错误来自他们使用函数之外的 return。

标签: r try-catch


【解决方案1】:

当您手动触发warning 时,您的表达式也会引发错误,因为您在函数外部使用return

如果您在function(e) 中返回错误消息本身(而不是打印“错误”),这会变得更加明显:

tryCatch({
  1+1
  warning("test")
  return(2)
}, error=function(e) {
  e
})

# <simpleError in doTryCatch(return(expr), name, parentenv, handler): 
#  no function to return from, jumping to top level>
# Warning message:
# In doTryCatch(return(expr), name, parentenv, handler) : test

(注意这相当于排除error 参数。)

这与您在 R 控制台输入 return(2) 时看到的错误消息相同:

return(2)
# Error: no function to return from, jumping to top level

要解决此问题,请从表达式中删除 return 调用,如下所示:

tryCatch({
  1+1
  warning("test")
  2
}, error=function(e){
  print('error')
})

# [1] 2
# Warning message:
# In doTryCatch(return(expr), name, parentenv, handler) : test

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2011-01-05
    • 2018-04-22
    相关资源
    最近更新 更多