例外未在node.js附加中捕获

exception not caught in node.js add-on

本文关键字:js node      更新时间:2023-10-16

我目前正在根据armadillo线性代数库的对象包装编写包装程序类。我已经注意到,当armadillo发出异常时,即使我尝试处理例外,也不会捕获附加代码:

if(args[0].isString()){
    try{
        std::string s(*v8::String::AsciiValue(args[0]->ToString()));
        MatrixWrap* matrix = new MatrixWrap(s);
        matrix->Wrap(args.This());
    }catch(exception& e){
        cout << "caught exception" << endl;  // this code is never called.
    }
}

下面给出了相应的相应构造函数(_matrix是Arma :: Mat的一个实例,如果字符串未正确格式化,则引发异常):

MatrixWrap::MatrixWrap(string s):_matrix(s){
}

运行代码时,我将获得以下输出:

> var arma = require('./build/Release/armadillo');
> var matrix = new arma.Matrix('1 0; 0 1');
> matrix.print();
1.0000        0
    0   1.0000
> var B = new arma.Matrix('1 0; 0');
error: Mat::init(): inconsistent number of columns in given string
libc++abi.dylib: terminate called throwing an exception
Abort trap: 6

尽管捕获子句

,好像没有处理异常

而不是 catch(异常&amp; e),尝试使用 catch(...),它应该捕获所有例外。p>根据错误,Armadillo抛出STD :: LOGIC_ERROR,STD :: BAD_ALLOC或STD :: RUNTIME_ERROR

修改的构建脚本以启用异常处理:

{
    "targets": [
        {
            'target_name': 'armadillo',
            'sources':[ "src/addon.cpp", "src/MatrixWrap.cpp"],
            'link_settings': {
                'libraries': ['-larmadillo']
            },
            'cflags': ['-fexceptions'],
            'cflags_cc': ['-fexceptions']
        }
   ]
}