异常处理
tryCatch()函数捕获异常
用法:
tryCatch(
{
expr
},
warning = function(w)
{
warning-handler-code
},
error = function(e)
{
error-handler-code
},
finally
{
cleanup-code
}
)
如果调用tryCatch函数时出现一个错误,则会返回一个对象,该对象继承error类。 The key to using tryCatch is realising that it returns an object. If there was an error inside the tryCatch then this object will inherit from class error.
对于error = function(e)参数,参数e是代码产生的错误信息。 What happens is that this argument catches any error messages that originate in the expression that you are tryCatching. If an error is caught, it gets returned as the value of tryCatch. The argument e inside error=function(e) is the error message originating in your code.
参考 https://stackoverflow.com/questions/12193779/how-to-write-trycatch-in-r
https://stackoverflow.com/questions/8093914/skip-to-next-value-of-loop-upon-error-in-r-trycatch
try()函数
处理error的简单方式:
- try is a wrapper to run an expression that might fail and allow the user's code to handle error-recovery.
- try evaluates an expression and traps any errors that occur during the evaluation. If an error occurs then the error message is printed to the stderr connection unless options("show.error.messages") is false or the call includes silent = TRUE. The error message is also stored in a buffer where it can be retrieved by geterrmessage. (This should not be needed as the value returned in case of an error contains the error message.)
用法:
try(expr, silent = FALSE, outFile = getOption("try.outFile",
default = stderr()))
参数:
- expr :an R expression to try.
- silent:logical: should the report of error messages be suppressed?
- outFile:a connection, or a character string naming the file to print to (via cat(*, file = outFile)); used only if silent is false, as by default.