R语言try()错误识别将可能会报错的命令行放到try函数中并将其赋值到一个变量。tryCatch()函数可以根据表达式的Warning或者Error信息做出相应的操作。
Description
try
is a wrapper to run an expression that might fail and allow the user's code to handle error-recovery.
Usage
try(expr, silent = FALSE, outFile = getOption("try.outFile", default = stderr()))
### 1. try语句
f <- try(fisher.test(mutMat[, i], mutMat[, j]), silent = TRUE)
# 如果报错,则为try-error类型
if (class(f) == "try-error") f = NA
else f$estimate
# try() 函数一般与next 和 break 进行联用,next跳过本次循环,break跳出循环
### 2. tryCatch语句
tryCatch({expr1.. ## 需要运行的语句
},error = function(e){
expr2.. ## 当遇到error时运行的语句
},warning = function(w){
expr3.. ## 当遇到warning时运行的语句
}),finally = function(f){
expr4.. ## 这是正常时运行的语句
})
#当expr中既有warning,又有error时,warning的优先级靠前。