You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何自定义std::exception派生类无法被父类引用捕获?

问题分析:自定义异常无法被std::exception引用捕获的原因

嘿,这个问题我之前也碰到过!核心原因是C++类默认的继承权限在搞鬼——你的Exception类继承std::exception时用了默认的私有继承,这就导致基类的引用没法绑定到派生类对象,自然catch (std::exception& e)块抓不到抛出的异常了。

具体原因拆解

在C++中,使用class关键字定义类时,默认的继承方式是私有继承(private),所以你的代码里:

class Exception : std::exception { ... }

等价于:

class Exception : private std::exception { ... }

私有继承会切断派生类到基类的隐式向上转换路径,也就是说Exception对象无法被当作std::exception的引用使用,这就是catch块无法捕获异常的关键。

修正后的代码

只需要把继承方式显式改为public,同时别忘了补上std::exception所在的<exception>头文件(原代码漏了这个,虽然部分编译器可能间接包含,但标准写法必须显式引入):

#include <iostream>
#include <exception>  // 必须包含的头文件

class Exception : public std::exception {  // 显式指定public继承
public:
    const char* what() const noexcept override {
        return "test";
    }
};

int main() {
    try {
        throw Exception();
    } catch (std::exception& e) {
        std::cout << e.what() << std::endl;
    }
}

现在用g++ -std=c++17编译运行,就能正常捕获并输出test了。

内容的提问来源于stack exchange,提问作者Joald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:19:13