6

如何确保在“捕获”错误并记录它之后不再执行代码步骤(我不想使用 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 end execution...") 被执行?在错误处理函数中记录错误后停止代码处理的正确策略是什么?

4

1 回答 1

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.
于 2012-09-24T23:44:11.857 回答