使用常见的catch std :: exception块的C++ std :: system_error用法

var*_*ard 6 c++ exception c++11

std::system_error处理带有相关错误代码的异常.是否可以使用公共catch块来获取std :: system_error异常消息及其代码?像这样

try{
    // code generating exception
} catch (const std::exception& ex){ // catch all std::exception based exceptions
    logger.log() << ex.what();      // get message and error code
                                    // if exception type is system_error     
}
Run Code Online (Sandbox Code Playgroud)

唯一的方法是直接捕获std::system_error类型并在基类异常类型捕获之前获取其代码吗?广泛使用std :: system_error的最佳方法是什么?

eer*_*ika 8

广泛使用std :: system_error的最佳方法是什么?

在我看来,最好的方法是直接捕获异常.

catch (const std::system_error& e) {
    std::cout << e.what() << '\n';
    std::cout << e.code() << '\n';
} catch (const std::exception& e) {
    std::cout << e.what() << '\n'; 
}
Run Code Online (Sandbox Code Playgroud)

唯一的方法是直接捕获std :: system_error类型并在基类异常类型捕获之前获取其代码吗?

从技术上讲,这不是唯一的方法.这是显而易见的惯用方式.你可以dynamic_cast.

catch (const std::exception& e) {
    std::cout << e.what() << '\n';
    auto se = dynamic_cast<const std::system_error*>(&e);
    if(se != nullptr)
        std::cout << se->code() << '\n';
}
Run Code Online (Sandbox Code Playgroud)

但是你在评论中提到你不想使用dynamic_cast.也可以避免这种情况,但不能以任何方式有任何优势.

请注意,即使您可以以非显而易见的方式执行操作,但这并不意味着您应该这样做.