r - 在R中出现错误消息后添加更多详细信息

标签 r error-handling try-catch

我有一个类似于下面在循环内创建矩阵的函数。

foo <- function(x, y, z) {
  out <- list(a1 = NULL, a2 = NULL, a3 = NULL)
  for (i in 1:3) {
    t <- 100 * i
    a <- matrix(x, y + t, z)
    out[[i]] <- t(a)
  }
  return(out)
}

以下运行正常。
p <-foo(NA,100,50)

但是以下给出了cannot allocate vector of length错误
q <- foo(NA, 3500000, 50)

我想在函数中出现messageadjust arguments 'y' and 'z'错误之后添加一些其他cannot allocate vector of length,例如too many elements specified

我正在尝试trytryCatch,但是当错误在循环内发生时,似乎无法获得所需的结果。这该怎么做?

最佳答案

您可以使用简单的装饰器模式来丰富错误消息:

safify <- function(f){
    function(...){
        tryCatch({
            f(...)
        },
        error=function(e){
            msg=conditionMessage(e)
            if(grepl("cannot allocate", msg)){
                msg=paste(msg, " Adjust arguments 'y' and 'z'", sep='.')
                return(msg)
            }
            msg
        })
    }
}

safefoo = safify(foo)

#res=safefoo(NA, 3500000, 50)
#> res
#[1] "cannot allocate vector of size 667.6 Mb. Adjust arguments 'y' and 'z'"

这样,您可以捕获可能发生的每种错误,并丰富所需的错误。

关于r - 在R中出现错误消息后添加更多详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27598228/

相关文章:

r - 如果在一定的时间范围内,如何在 R 中赋值?

python - Python- “Local x variable referenced before assignment”(关闭)

design-patterns - 忽略(严重)错误以使程序继续运行?

在 try catch block 中执行 SQL 查询时出现 java.lang.NullPointerException 错误

r - 按行计算超过数据框中值的列数

r - 我想从 R 中的两列中选择两个值中较大的一个

r - 如何在 Shiny 的开始时将投递箱清空

python - Python中的异常处理是如何实现的?

PHP 7 try catch : unable to catch "Catchable fatal error"

python - python 中 try 和 except 的使用