【问题标题】:How to prevent execution of further code steps after error?错误后如何防止执行进一步的代码步骤?
【发布时间】:2012-09-16 10:07:54
【问题描述】:

如何确保在“捕获”错误并记录错误后不再执行代码步骤(我不想使用 q())?

我的使用场景是这样的: - 做一些计算 - 如果发生错误记录它 - 停止在代码中执行任何进一步的步骤

我尝试使用下面的代码示例来解决这个问题(使用打印而不是真正的日志记录功能):

handleMySimpleError<-function(e, text) {
    # Let's log the error
    print(paste0(text, ": ", e))
    # This should stop execution of any further steps but it doesn't
    stop("Now, stop. For real.")
}

print("Starting execution...")
tryCatch(
    stop("My simple error."),
    error=function(e) {handleMySimpleError(e, "could not finish due to")}, finnaly=NULL
)
print("Successfully ended execution...")

我不知何故希望 print("Successfully end execution...") 永远不会被执行...但是,这是我得到的输出:

> handleMySimpleError<-function(e, text) {
+   # Let's log the error
+   print(paste0(text, ": ", e))
+   # This should stop execution of any further steps but it doesn't
+   stop("Now, stop. For real.")
+ }
>  
> print("Starting execution...")
[1] "Starting execution..."
> tryCatch(
+   stop("My simple error."),
+   error=function(e) {handleMySimpleError(e, "could not finish due to")}, finnaly=NULL
+ )
[1] "could not finish due to: Error in doTryCatch(return(expr), name, parentenv, handler): My simple error.\n"
Error in handleMySimpleError(e, "could not finish due to") : 
Now, stop. For real.
> print("Successfully ended execution...")
[1] "Successfully ended execution..."

如何防止 print("Successfully ends execution...") 被执行?在错误处理函数中记录错误后停止代码处理的正确策略是什么?

【问题讨论】:

  • 你是如何执行该代码的?采购脚本?
  • 我现在正在使用 Ctrl+R+R 通过 StatEt Eclipse 插件对其进行测试。我想在“生产”中使用“脚本”,例如:/usr/bin/R --vanilla --quiet
  • 当我将该代码放入脚本并获取它时,它似乎可以按您的意愿工作。如果我直接将其发送到控制台,我会得到您在问题中描述的行为。
  • 乔兰谢谢。您是否知道解决方法或更合适的策略来实现我想要的(这适用于所有执行场景:脚本和控制台)?
  • 我怀疑更好的策略是不要通过将代码直接发送到控制台来尝试这样做。无论如何,采购脚本通常更适合生产代码。

标签: r


【解决方案1】:

用花括号把它包起来

>     {
+       handleMySimpleError<-function(e, text) {
+           # Let's log the error
+           print(paste0(text, ": ", e))
+           # This should stop execution of any further steps but it doesn't
+           stop("Now, stop. For real.")
+       }
+       print("Starting execution...")
+       tryCatch(
+           stop("My simple error."),
+           error=function(e) {handleMySimpleError(e, "could not finish due to")}, finally=NULL
+       )
+       print("Successfully ended execution...") 
+     }
[1] "Starting execution..."
[1] "could not finish due to: Error in doTryCatch(return(expr), name, parentenv, handler): My simple error.\n"
Error in handleMySimpleError(e, "could not finish due to") : 
  Now, stop. For real.

【讨论】:

  • 谢谢。伟大的。我只需要弄清楚为什么使用花括号实际上有效,为什么不使用它们... :) 这对我来说是违反直觉的。将咨询 Pat Burns R Inferno。
  • 问题是您一次执行 1 行。因此,在stop 之后,您会收到一条错误消息,然后执行下一行。如果你用大括号括起来,你实际上是在告诉 R,“一次运行整个块,而不是逐行运行”。现在,当它遇到错误时,它会退出代码块。
  • 我现在看到了。谢谢你。这更有意义。我假设处理是以与 SAS 类似的方式完成的......
猜你喜欢
  • 1970-01-01
  • 2016-06-12
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
相关资源
最近更新 更多