介绍
tryCatch()函数可以根据表达式的Warning或者Error信息做出相应的操作。
函数用法
tryCatch({
expr
}, warning = function(w){
# 这里是出现warning状态时,应该怎么做,可以用print打印出来,可以执行其它命令
}, error = function(e){
# 这里时出现Error状态时,应该怎么做,可以用print打印出来,也可以执行其它命令
},finally = {
# 这是运行正常时,应该怎么做,可以用print打印出来,也可以执行其它命令
})
实例
library(data.table)
dd = data.frame(ID = 1:10,y= rnorm(10))
dd
# warning
re1 = dcast(dd,y~.)
re1
这个时候会报告warning的信息:
> re1 = dcast(dd,y~.)
Using 'y' as value column. Use 'value.var' to override
Warning message:
In dcast(dd, y ~ .) :
The dcast generic in data.table has been passed a data.frame and will attempt to redirect to the reshape2::dcast; please note that reshape2 is deprecated, and this redirection is now deprecated as well. Please do this redirection yourself like reshape2::dcast(dd). In the next version, this warning will become an error.
如果使用tryCatch()函数:
re1 = tryCatch({
dcast(dd,y~.) # warning
# aaaaa # error
},warning = function(w){
2
print("warning")
},error = function(e){
3
print("error")
})
re1
# warning
re1 = tryCatch({
dcast(dd,y~.) # warning
# aaaaa # error
},warning = function(w){
2
print("warning")
6
},error = function(e){
3
print("error")
})
re1
#[1] 6
可见tryCatch()返回的值是函数中的最后一行代码