【问题标题】:C++ std::system_error usage with common catch std::exception blockC++ std::system_error 与通用 catch std::exception 块的用法
【发布时间】:2014-05-14 10:08:36
【问题描述】:

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     
}

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

【问题讨论】:

  • 嗯,也许您可​​以尝试使用dynamic_cast 检查,但您只需抓住std::system_error 有什么困扰?
  • @πάντα 没关系,如果存在更简洁的方式,我会很有趣。我不喜欢使用dynamic_cast
  • 为什么不明确地捕捉system_error

标签: c++ exception c++11


【解决方案1】:

广泛使用 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'; 
}

唯一的方法是直接捕获 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';
}

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

请注意,即使您可以以不明显的方式做事,也不意味着您应该

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多