【问题标题】:Why does withCallingHandlers still stops execution?为什么 withCallingHandlers 仍然停止执行?
【发布时间】:2015-11-17 00:43:19
【问题描述】:

似乎withCallingHandlers 实际上并没有像tryCatch 那样捕获错误并且脚本仍然停止执行。

将 sn-p 与 tryCatch 进行比较,其中 "before" 和 "after" 都被打印:

f1 <- function() {
  cat("before tryCatch\n")
  tryCatch({
      stop("this is an error!")
    },
    error = function(cond) {
      print(cond$message)
    }
  )
  cat("after tryCatch\n")
}

使用与withCallingHandlers 相同的 sn-p,不打印“之后”并停止执行:

f2 <- function() {
  cat("before tryCatch\n")
  withCallingHandlers({
      stop("this is an error!")
    },
    error = function(cond) {
      print(cond$message)
    }
  )
  cat("after tryCatch\n")
}

我做错了什么?

一些背景

我想使用withCallingHandlers 来分析使用sys.calls() 发生错误时的调用堆栈。

根据Advanced R 应该是可以的:

withCallingHandlers() 中的处理程序在生成条件的调用上下文中调用,而tryCatch() 中的处理程序在tryCatch() 的上下文中调用。

【问题讨论】:

  • 似乎用tryCatch包裹withCallingHandlers可以解决问题,但看起来有点丑。
  • 简单地说withCallingHandlers中的error参数用于向函数发出错误信号,但没有建立从错误中恢复的错误处理程序。这只能通过使用tryCatch来实现。

标签: r error-handling


【解决方案1】:

调用处理程序提供了一种在通过过程中“触摸”条件的方式,可能会在交互式会话中向用户发出信号之前将错误记录到文件中。

如果调用处理程序实际上没有返回,调用处理程序可用于“消除”警告、消息或错误。您可以使用重新启动使调用处理程序不返回 - 将您希望在对 withRestarts() 的调用中继续执行的代码括起来,并在处理程序中调用重新启动:

f2 <- function() {
  cat("before tryCatch\n")
  withCallingHandlers({
      withRestarts({
          stop("this is an error!")
      }, muffleStop=function() {
          message("'stop' muffled")
      })
    },
    error = function(cond) {
      print(cond$message)
      invokeRestart("muffleStop")
    }
  )
  cat("after tryCatch\n")
}

更常见的是,重新启动是在一段代码中建立的(如在内置函数 warning 中)并在完全独立的代码段中调用(如内置函数 suppressWarnings

> warning
function (..., call. = TRUE, immediate. = FALSE, noBreaks. = FALSE, 
    domain = NULL) 
{
        ##
        ## ...
        ##
        withRestarts({
            .Internal(.signalCondition(cond, message, call))
            .Internal(.dfltWarn(message, call))
        }, muffleWarning = function() NULL)
        ##
        ## ...
        ##
}
<bytecode: 0x51a4730>
<environment: namespace:base>
> suppressWarnings
function (expr) 
{
    ops <- options(warn = -1)
    on.exit(options(ops))
    withCallingHandlers(expr, 
        warning = function(w) invokeRestart("muffleWarning"))
}
<bytecode: 0x35c2a60>
<environment: namespace:base>

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 2011-11-05
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多