【问题标题】:How to catch any c++ standard exception?如何捕捉任何 C++ 标准异常?
【发布时间】:2019-04-01 21:35:00
【问题描述】:

我知道在 C++ 中,您可以使用以下方法捕获任何数据类型的异常:

try {
  // throw exception here
} catch (...) {
  // handle exception here
}

但我想捕获任何 C++ 标准异常,例如 std::logic_errorstd::out_of_range,而不是其他数据类型,例如 stringint。如何仅捕获 C++ 标准异常?我想在传入的 C++ 标准异常对象上调用exp.what(),而使用上面的代码是不可能的。

【问题讨论】:

标签: c++ exception-handling


【解决方案1】:

所有标准异常都源自std::exception,因此请抓住它:

try {
    // throw exception here
}
catch (const std::exception &e) {
    // handle exception here
}

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 2013-03-29
    • 2015-12-19
    • 2012-03-20
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多