R:tryCatch()语法中的错误处理

R:tryCatch()语法中的错误处理,r,error-handling,try-catch,R,Error Handling,Try Catch,我试图了解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

我试图了解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 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())
    语法是否不正确


  • 谢谢

    错误
    需要一个函数。您传递了一个表达式,该表达式是对参数计算函数的结果。另外,
    错误
    未将数据帧传递到
    。传递错误文本

    替换此:

    myVal2 <- tryCatch(foo(d2), error = bar(d2))
    

    你可能会发现你救了我的饭碗!谢谢
    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
    <simpleError in `[.data.frame`(dat, , "r3"): undefined columns selected>