我试图了解R中的错误处理。从阅读文档,我找不到正确语法的明确定义。
以下是一个自包含的示例:
foo <- function(dat) {
print('Calling foo()')
print(dat[,'r1'])
print(dat[,'r2'])
print(dat[,'r3'])
print('Finished foo()')
return(dat$r3)
}
bar <- function(dat) {
print('Calling bar()')
print(dat[,'r1'])
print(dat[,'r2'])
print('Finished bar()')
return(dat$r2)
}
d1 <- data.frame(r1 = 1:10, r2 = 11:20, r3 = 21:30)
d2 <- d1[c("r1", "r2")]
print('Starting')
print('trying d1')
myVal1 <- tryCatch(foo(d1), error = bar(d1))
print('finished d1')
print('trying d2')
myVal2 <- tryCatch(foo(d2), error = bar(d2))
print('finished d2')
print('Done')
预期产出:
[1] "Starting"
[1] "trying d1"
[1] "Calling foo()"
[1] 1 2 3 4 5 6 7 8 9 10
[1] 11 12 13 14 15 16 17 18 19 20
[1] 21 22 23 24 25 26 27 28 29 30
[1] "Finished foo()"
[1] "finished d1"
[1] "trying d2"
[1] "Calling bar()"
[1] 1 2 3 4 5 6 7 8 9 10
[1] 11 12 13 14 15 16 17 18 19 20
[1] "Finished bar()"
[1] "finished d2"
[1] "Done"
实际输出:
[1] "Starting"
[1] "trying d1"
[1] "Calling bar()"
[1] 1 2 3 4 5 6 7 8 9 10
[1] 11 12 13 14 15 16 17 18 19 20
[1] "Finished bar()"
[1] "Calling foo()"
[1] 1 2 3 4 5 6 7 8 9 10
[1] 11 12 13 14 15 16 17 18 19 20
[1] 21 22 23 24 25 26 27 28 29 30
[1] "Finished foo()"
[1] "finished d1"
[1] "trying d2"
[1] "Calling bar()"
[1] 1 2 3 4 5 6 7 8 9 10
[1] 11 12 13 14 15 16 17 18 19 20
[1] "Finished bar()"
[1] "Calling foo()"
[1] 1 2 3 4 5 6 7 8 9 10
[1] 11 12 13 14 15 16 17 18 19 20
Error in tryCatchOne(expr, names, parentenv, handlers[[1L]]) :
attempt to apply non-function
我的问题:
为什么这个tryCatch()
调用最终会同时运行这两个函数?
为什么我会收到上面报告的错误?
我的tryCatch(someFunction(), error = someOtherFunction())
语法不正确吗?
谢谢!
答案 0 :(得分:2)
error
需要一个功能。您已经传递了一个表达式,该表达式是对参数求值函数的结果。此外,error
未将数据框传递给bar
。传递错误文本。
取而代之:
myVal2 <- tryCatch(foo(d2), error = bar(d2))
用这个:
myVal2 <- tryCatch(foo(d2), error = function(e) { cat('In error handler\n'); print(e); e })
导致此行为:
[1] "Calling foo()"
[1] 1 2 3 4 5 6 7 8 9 10
[1] 11 12 13 14 15 16 17 18 19 20
In error handler
<simpleError in `[.data.frame`(dat, , "r3"): undefined columns selected>
请注意调用该处理程序。 myVal2
设置为错误处理程序的结果:
> myVal2
<simpleError in `[.data.frame`(dat, , "r3"): undefined columns selected>