tryCatch函数的使用

Usage of tryCatch function

我想使用 R 中的 trycatch 函数来检查给定值是否为整数,如果不是 return 错误。我当前的代码如下所示,它不起作用。

 b <- function() as.integer(n_top_features)
  tryCatch ( {
    error = function(e){
      b()
    }
  },
    stop('ERROR: n_top_features variable should be integer!')
 )

如果您阅读 documentation of the tryCatch function,您会看到以下用法:

tryCatch(expr, ..., finally)

即:您想要“尝试”的实际表达式是第一个参数,处理程序(您尝试编写的)随后出现:

tryCatch(
    as.integer(n_top_features),
    error = function (e) {
        stop('ERROR: n_top_features variable should be integer!')
    }
)

但是,那也不行;原因是当参数不能转换为整数时 as.integer 不会引发错误。它会引发 warning。所以你的 tryCatch 需要安装一个 warning 处理程序:

result = tryCatch(
    as.integer(n_top_features),
    warning = function (w) {
        stop('ERROR: n_top_features variable should be integer!')
    }
)