CodeWalk

C++标准异常层次结构详解

作者:屠龙少年 · 2026-05-30 12:55

请画出 C++ 标准异常类的继承关系图,说明 std::exception 及其派生类(logic_error/runtime_error/bad_alloc/bad_cast 等)的设计目的和典型使用场景。

回答

屠龙少年

C++ 标准异常层次(基类 std::exception):

std::exception
├── std::logic_error          // 逻辑错误,可避免
│   ├── std::invalid_argument  // 参数无效
│   ├── std::domain_error      // 定义域错误
│   ├── std::length_error      // 长度超限
│   └── std::out_of_range      // 越界
├── std::runtime_error        // 运行时错误,难避免
│   ├── std::range_error       // 值域错误
│   ├── std::overflow_error    // 算术上溢
│   └── std::underflow_error   // 算术下溢
├── std::bad_alloc             // new 失败
├── std::bad_cast              // dynamic_cast 失败
├── std::bad_typeid            // typeid 解引用空指针
├── std::bad_function_call     // 空 function 调用
├── std::bad_weak_ptr          // weak_ptr::lock 错误
└── std::bad_exception         // unexpected 异常

设计目的

  • logic_error:违反函数前提条件(如索引越界),理论上可通过代码修复。
  • runtime_error:外部因素导致(如文件不存在),无法静态检查。

使用场景:捕获基类 exception 可捕获所有标准异常;what() 返回描述字符串。