c++ - 捕获异常 : error: svd() failed to converge

标签 c++ rcpp armadillo

我编写了一个使用 Armadillo svd_econ 函数的函数。我正在尝试处理 svd 无法收敛的情况,因为出于某种原因在这种情况下它不会中止函数。

有问题的错误是:

error: svd_econ(): failed to converge

根据我对 SVD documentation 的阅读,这应该抛出一个 std::runtime_error,并且根据我对 Exceptions tutorial 的阅读,我应该可以这样处理:

arma::mat U, V;
arma::vec S;
try {
  // aDat and subsetRows are previously defined
  arma::svd_econ(U, S, V, aDat.rows(subsetRows), "right", "dc");
} catch (std::runtime_error e) {
  std::cout << "Exception caught!" << std::endl;
  // I want to abort, and return the error to R:
  throw Rcpp::exception(e.what());
}

但是,当我运行此代码时出现了上面的错误消息,我得到了一个段错误。如果我删除 try-catch block ,代码会继续运行,并在代码尝试使用 SVD 的结果时进一步抛出错误。

我想我只是遗漏了一些明显的东西,因为我还没有正式学习任何 C++

最佳答案

看起来不错,我只是尝试一些事情:

  • 对异常的引用,
  • 只是将错误转发给 R,而不是另一个 throw()
  • 带有 Rf_error() 的默认 block

所以也许(未经测试)

try {
  arma::svd_econ(U, S, V, aDat.rows(subsetRows), "right", "dc");
} catch (std::runtime_error & e) {
  std::cout << "Exception caught!" << std::endl;
  forward_exception_to_r(e);
} default(...) {
  Rf_error("Unknown exception");
}

但本质上,您可以通过 Rcpp 属性免费获得所有这些,因为这是(自动插入的)END_RCPP 宏所做的——有关更多详细信息,请参阅 Rcpp 手册的第 2.7 节。

编辑 但是@mtall 在他的评论中做了我们应该首先做的事情:检查 Armadillo 文档。所以你可以简单地检查返回值。但您可能也想尝试建议的 try/catch。

关于c++ - 捕获异常 : error: svd() failed to converge,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24966691/

相关文章:

c++ - 如何获取进程中使用的 .DLL 的(物理)基地址?

c++ - Rcpp NumericalMatrix 数据类型,全局声明

c++ - Bool 排序插入函数,检查 int 是否已存在于列表中

c++ - std::condition_variable 仅在调试时有效?

c++ - 如何在 Xcode 中追踪 "libc++abi.dylib: Pure virtual function called!"

c++ - 在 Rcpp(和 RcppArmadillo)中,如何检查 vec 是否包含复数?

r - loadNamespace(name)中的错误:没有名为 'Rcpp'的软件包

c++ - 错误 : reference to ‘sword’ is ambiguous in armadillo and oracle occi compatibility issue

linker - Rcpp 错误 :/usr/bin/ld cannot find -lgfortran

r - 需要Rcpp软件包中使用的OpenMP可用性