2026-02-02 08:42:56
在 C++ 中,捕获特定类型的异常主要通过 try-catch 块实现,其中 catch 子句需明确指定异常类型。以下是具体方法和实战案例:
核心方法使用引用(如 const std::exception&)避免切片,并保留派生类信息。
通过 e.what() 获取异常描述(适用于 std::exception 派生类)。
以下代码演示如何捕获 std::runtime_error 类型的异常(例如文件不存在时抛出):
#include <iostream>#include <fstream>#include <stdexcept> // 包含 std::runtime_errorvoid read_file(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error("File not found: " + filename); } // 正常读取文件内容...}int main() { try { read_file("nonexistent.txt"); // 尝试读取不存在的文件 } catch (const std::runtime_error& e) { std::cerr << "Caught exception: " << e.what() << std::endl; } catch (...) { // 捕获其他所有异常(可选) std::cerr << "Unknown exception caught." << std::endl; } return 0;}关键点说明异常类型匹配:
catch (const std::runtime_error& e) 仅捕获 std::runtime_error 及其派生类异常。
若需捕获所有标准异常,可使用 catch (const std::exception& e)。
省略异常类型(如 catch (...))可捕获任意异常,但会丢失类型信息。
异常传播:
若 catch 块未处理异常,异常会继续向上传播(例如从函数内部抛出到调用者)。
自定义异常:
可通过继承 std::exception 定义自定义异常类型,并在 catch 中捕获:class MyException : public std::exception {public: const char* what() const noexcept override { return "My custom exception"; }};// 抛出和捕获...
通过以上方法,可以精准捕获并处理特定类型的异常,提升代码健壮性。