如何防止错误后执行更多代码步骤?

时间:2012-09-24 22:12:03

标签: r

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

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

我尝试使用下面的代码示例解决此问题(使用print代替真正的日志记录功能):

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...")

我不知何故希望打印(“成功结束执行...”)永远不会被执行......但是,这是我得到的输出:

> 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..."

如何防止执行打印(“成功结束执行...”)?在错误处理函数中记录错误后停止代码处理的正确策略是什么?

1 个答案:

答案 0 :(得分:6)

只需将花括号括起来

>     {
+       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.