如何捕获Eigen的MatrixXd :: resize()函数引发的异常?

bob*_*obo -5 c++ exception-handling eigen

为什么我不能抓住这个例外?

我的(客户端)代码:

Eigen::MatrixXd FFs ;
try
{
  FFs.resize( NUMPATCHES, NUMPATCHES ) ;
}
catch( int e )
{
  error( "Not enough memory :(" ) ;
  return ;
}
Run Code Online (Sandbox Code Playgroud)

抛出异常的特征代码是向下几级.

    EIGEN_STRONG_INLINE void resize(Index rows, Index cols)
    {
        internal::check_rows_cols_for_overflow(rows, cols);
        m_storage.resize(rows*cols, rows, cols);
    }

哪个电话

    void resize(DenseIndex size, DenseIndex rows, DenseIndex cols)
    {
      if(size != m_rows*m_cols)
      {
        internal::conditional_aligned_delete_auto(m_data, m_rows*m_cols);
        if (size)
          m_data = internal::conditional_aligned_new_auto(size);
        else
          m_data = 0;
        EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN
      }
      m_rows = rows;
      m_cols = cols;
    }

粗体线是在线前被击中的线:

throw std::bad_alloc();
Run Code Online (Sandbox Code Playgroud)

被击中,这发生在internal::conditional_aligned_delete_auto(m_data, m_rows*m_cols);函数调用中的某个地方.

为什么我不能从客户端代码中捕获此异常?是因为Eigen库没有标记resize功能throws吗?如何使用Eigen库使此代码malloc顺利从此类型错误中恢复?

fin*_*man 12

您必须捕获正确的异常类型.使用:

catch( std::exception &e )
Run Code Online (Sandbox Code Playgroud)

代替:

catch( int e )
Run Code Online (Sandbox Code Playgroud)


小智 8

catch( std::bad_alloc& e) {
}
Run Code Online (Sandbox Code Playgroud)

应该有所帮助


And*_*adt 6

您正在捕获类型的异常int,而抛出的实际异常是类型std::bad_alloc().

catch (std::bad_alloc& e)
{
    exit(1); // or some other appropriate behavior
}
Run Code Online (Sandbox Code Playgroud)

可能就是你想要的.