【发布时间】: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