R中的嵌套Try Catch

时间:2016-03-01 06:47:34

标签: r

我正在尝试在R中实现嵌套的tryCatch。代码如下:

tryCatch({
    a <- 2/'a'
    print(a)
    print("himanshu")

    tryCatch({
        a <- 3/'a'
        print(a)
        print("inner loop") 

    }, warning = function(war) {
        print("Warning in inner tryCAtch")

    },  error = function(err) {
        print("Error in inner tryCAtch")
    })

 }, warning = function(war) {
        print("Warning in outer tryCAtch")

 }, error = function(err) {
    print("Error in outer tryCAtch")

 })

即使内部块中存在错误,也会打印外部块的消息。我希望输出像:

Error in inner block
Error in outer block

2 个答案:

答案 0 :(得分:4)

我认为你有两个问题,第一个是tryCatch()在发生错误时停止执行try-block,所以第二个tryCatch()永远不会执行。第二个问题是你似乎混合了try / catch的目的。

通常,我在三种情况中的一种情况下使用tryCatch()(1)从失败中恢复,(2)关闭打开的资源,以及(3)通过更好的错误消息传递错误。

如果你想从失败中恢复过来,那就最好了 在try块中只包含一个语句,否则你的错误处理程序必须有逻辑来识别哪个语句失败,这可能会变得很难看。

tryCatch({
    a_statement_that_might_fail()

},error = function(err){
    recover from failure here

})

如果您只需要更好的错误消息或关闭开放资源,可以使用多语句try-block:

resource  <-  open_file_or_database()
tryCatch({
    lots()
    of()
    statements()
    that()
    might()
    fail()

},error = function(err){
    stop(sprintf('Got this error: %s',err$message)) 

},finally={
    close(resource)

})

答案 1 :(得分:0)

您确定,错误不会导致两个try块停止吗?这会导致你描述的行为。

我无法重现这个问题,所以这是一个积极的例子:

## Example of nested tryCatch

# set this variable to 'outer_error', 'outer_warning', 'inner_error', 'inner_warning' or empty ('') to see the different scenarios
case <- "inner_error"

result <- "init value"

tryCatch({

  if( case == "outer_error") {
    stop( simpleError("Whoops: outer error") )
  }

  if( case == "outer_warning") {
    stop( simpleWarning("Whoops: outer warning") )
  }

  result <- "first result"

  tryCatch({
    if( case == "inner_error") {
      stop( simpleError("Whoops: inner error") )
    }

    if( case == "inner_warning") {
      stop( simpleWarning("Whoops: inner warning") )
    }

    result <- "Second result!"
  },
  error = function(e) {
    print(sprintf("Inner error: %s", e)) 
  },
  warning = function(e) {
    print(sprintf("Inner warning: %s", e))
  },
  finally = {
    print(sprintf("Inner tryCatch all done, result is %s", result))
  })
},
warning = function (e) {
  print(sprintf("Outer Warning: %s", e) )
},
error = function(e) {
  print(sprintf("Outer Error: %s", e))
},
finally = {
  print(sprintf("And the result is: %s", result))
})
相关问题