cry*_*111 5 exception-handling r stack-unwinding
为了为我的同事和我的R脚本建立一个连贯的异常处理接口,我想使用以下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);}
)
Run Code Online (Sandbox Code Playgroud)
只捕获一些错误,将其他错误留给外部处理程序或根本没有处理程序,这是完全正常的.错误系统比通常使用的更灵活,因此对于重新抛出错误,您可能会考虑创建自己的错误类型
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)))
}
Run Code Online (Sandbox Code Playgroud)
投掷和/或处理
tryCatch(vec*parameter1, error=function(e) {
err <- ourError(e, "addition fatal info; script aborted")
stop(err)
})
Run Code Online (Sandbox Code Playgroud)
这样做的一个优点是可以使用返回的类在顶级处理程序中指定其他行为 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)
})
Run Code Online (Sandbox Code Playgroud)