首页 > 解决方案 > 如何捕捉任何 C++ 标准异常?

问题描述

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

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

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

标签: c++exception-handling

解决方案


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

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

推荐阅读