首页 > 解决方案 > 错误函数内的变量声明

问题描述

我在函数的错误函数中有一个变量声明tryCatch。但是当错误触发时,即使成功输出了错误信息,也不会执行变量声明。

tryCatch({ var_binned_names = arules::discretize(Xt,
                                              method = arules_method,
                                              breaks = num_breaks,
                                              ordered = TRUE)
        }, error = function(error) {
          cat("Error: could not discretize numeric", numeric_i, "", name, "\n")
          cat("Unique values:", length(unique(Xt)), "\n")
          var_binned_names = Xt
        })

人们会期望,当var_binned_names由于离散化错误而无法分配时,它将Xt在错误函数中分配。但是,发生的情况是它没有定义。

标签: r

解决方案


使用这种方法:

Xt <- 1

res <- tryCatch({ stop("some error")
}, error = function(error) {
  cat("some error message")
  Xt
})

res
#[1] 1

tryCatch有返回值。它是表达式的返回值或(如果触发了错误等条件)处理程序的返回值。


推荐阅读