【问题标题】:How do you make tryCatch actually catch the error你如何让 tryCatch 真正捕捉到错误
【发布时间】:2014-10-17 19:31:15
【问题描述】:

如果参数不满足许多条件,我必须调用一个引发错误的函数。

条件非常复杂,以至于我无法 100% 地尝试满足它们(我必须重新键入函数内部检查的所有条件)。 相反,我应该使用不同的参数重试调用(根据需要多次调用以填充我的表)。

在其他语言中,我可以在调用周围编写一个 catch 块。

但是,在 R 中,tryCatch 的工作方式似乎有所不同:您可以使用 finally= 提供代码,但在执行 finally 代码后,外部函数无论如何都会终止。

这是一个最小的例子:

sometimesError <- function() {
    if(runif(1)<0.1) stop("err")
    return(1)
}
fct <- function() {
    theSum <- 0
    while(theSum < 20) {
        tryCatch( theSum <- theSum + sometimesError() )
    }
    return(theSum)
}
fct()    # this should always evaluate to 20, never throw error

(我已阅读 "Is there a way to source() and continue after an error?" 和其他一些帖子,但我认为它们不适用于此处。他们实现了源代码继续逐语句执行,而不管错误如何,就好像它在顶层执行一样。另一方面,我对被调用函数的终止感到满意,调用者代码应该继续)

【问题讨论】:

  • 不使用try(, silent = TRUE) 而不是tryCatch 给你你想要的吗?
  • 我前几天做过类似的事情,我会检查...
  • 面部护理。有用!请创建一个简短的答案,我会接受。谢谢!
  • @rawr。掌心。有用!请创建一个简短的答案,我会接受。谢谢!

标签: r error-handling try-catch


【解决方案1】:

您可以将函数传递给tryCatcherror 参数,以指定出现错误时应该发生的情况。在这种情况下,您可以在出错时返回 0

fct <- function() {
  theSum <- 0
  while(theSum < 20) {
    theSum <- theSum + tryCatch(sometimesError(), error=function(e) 0)
  }
  return(theSum)
}

正如 cmets 中提到的 @rawr,在这种情况下,您也可以将 tryCatch 替换为 try

fct <- function() {
  theSum <- 0
  while(theSum < 20) {
    try(theSum <- theSum + sometimesError(), silent=TRUE)
  }
  return(theSum)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2014-06-22
    • 2014-12-03
    • 1970-01-01
    • 2010-12-06
    相关资源
    最近更新 更多