为了为我的同事和我的r脚本设置一个连贯的异常处理界面,我想采用以下Trycatch结构。

  1. 外部替换被包裹在给定的r脚本周围。它用于捕获并处理要求脚本中止的致命错误。 用户脚本中的用户特定的rettcatch命令。这些应该抓住和,可能,处理
    • 2a。非致命错误,没有脚本堕胎是必要的
    • 2b。需要脚本中止的致命错误。误差由外部试用处理[参见1。]
    • 2c。致命误差具有附加错误信息。外部Trycatch处理错误。

      以下代码是我如何实现这些功能。但是,由于我不是R的专家,我想问一下这是否是一种很好的方法。具体:

      Q1。是否可以在内部Trycatch中指定错误处理程序并等待外部Trycatch处理该错误(请参阅2b。上面和下面的代码)?

      Q2。在处理程序中,重新缩写相同的错误(见2c。上/下方)正确/被认为是好的编码风格?

      谢谢!

      #outer tryCatch, see 1.
      tryCatch({
        #user code block
        #2a. user specific tryCatch, object "vec" not defined
        tryCatch(print(vec),error=function(e) {print("Non-fatal error. Script execution continued.");print(e);})
      
        #2b. user specific tryCatch
        tryCatch(vec*2)
      
        #2c. user specific tryCatch
        tryCatch(vec*parameter1, error=function(e) {print("Additional fatal error information. Script execution aborted.");stop(e);})
        #end of user code block
      },
           #outer tryCatch error handler in order to handle fatal errors
           error=function(e) {print("Fatal error");print(e);} 
          )
      
      .

有帮助吗?

解决方案

完全可以抓住一些错误,留下外部处理程序或根本没有处理程序。错误系统比通常使用的更灵活,因此可以考虑创建自己的错误类型

ourError <-
    function(original, message, class="ourError")
{
    msg <- paste(message, conditionMessage(original), sep="\n  ")
    structure(list(message = msg, call = conditionCall(original)),
              class = c(class, class(original)))
}
.

并投掷和/或处理

tryCatch(vec*parameter1, error=function(e) {
    err <- ourError(e, "addition fatal info; script aborted")
    stop(err)
})
.

其中一个优点是,可以在顶级处理程序中指定附加行为,使用ourError() 返回的类

tryCatch({
    tryCatch(stop("oops"), error=function(e) {
        err <- ourError(e, "addition fatal info; script aborted",
                      c("fatal", "ourError"))
        stop(err)
    })
}, ourError=function(err) {
    message("We caught but didn't handle this:\n", err)
}, error =function(err) {
    message("This one got away: ", err)
})
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top