无法通过引用 std::exception 来捕获从 std::exception 派生的类
Can't catch class derived from std::exception by reference to std::exception
我创建了一个派生自 std::exception 的自定义异常类。
#include <iostream>
class Exception : std::exception {
public:
const char* what() const noexcept override {
return "test";
}
};
int main() {
try {
throw Exception();
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
}
该程序在 Ubuntu 上由g++ -stdc++=17
编译时,会导致异常不会被catch
块捕获,即使通过引用捕获也应该捕获派生的异常。它调用std::terminate
,即使它发生在一个通过引用捕获其基类的try
块中。如果Exception
从std::runtime_error
继承并"test"
传递给其自己的构造函数中的std::runtime_error
构造函数,也会发生同样的事情。通常解决方案是仅使用Exception
捕获,但是在我的原始代码中,我需要捕获不同类型的异常,所有这些异常都继承自std::exception
。为什么会这样?参考基地捕捉不起作用吗?如何使用一个 catch 块捕获从std::exception
派生的所有异常?
在定义基类期间从基类继承class
时,继承的默认访问修饰符是private
。这意味着以下两个定义是等效的:
class derived : base { /* ... */ };
class derived : private base { /* ... */ };
该语言不允许1U 引用来自私有基2的派生类。例如,以下代码不编译:
int main()
{
derived d;
base& b = d; // <== compilation error
}
error: 'base' is an inaccessible base of 'derived' base& b = d; ^
wandbox.org 上的现场示例
这就是您的catch
块无法处理Exception
的原因。将您的继承更改为public
...
class Exception : public std::exception
。并且您的原始代码将起作用。
wandbox.org 上的现场示例
1参见 [dcl.init.ref] 和 [conv.ptr]。
2除非你属于derived
本身的范围。请参阅wandbox.org 上的这个实时示例。
你需要公开派生自std::exception
class Exception : public std::exception
那么你的输出是
test
有关本主题的更多详细信息,请参阅私有、公共和受保护继承之间的区别。
相关文章:
- 为重写std::exception的库生成swig接口时出错
- 什么是 std::exception::what() 以及为什么要使用它?
- 为什么程序员同时使用 std::bad_alloc 和 std::exception.是否 std::例外 仅是不够的
- 请参阅在 Visual Studio 2019 中捕获 std::exception 时对函数模板实例化消息的引用
- 派生自 std::exception 的类的赋值运算符
- std::exception :使用虚函数和继承与变量
- 这段 C++ 代码的奇怪行为(std::wcout 和 std::exception)
- 如何从 std::exception 到 std::nested_exception dynamic_cast?
- 如何捕获 I/O 异常(确切地说是 I/O,而不是 std::exception)
- 在 CLI 中抛出 std::exception 会引发访问冲突
- 为什么 std::exception 会在 std::bad_alloc 之前捕获我的异常
- 为什么人们将虚拟关键字放在std :: exception :: what()的面前
- C++通过继承 std::exception 来创建新的异常
- 运行时异常消息而不扩展 std::exception
- 从 std::exception 类和类型标识继承
- 捕获并修改 std::exception 和子类,重新抛出相同的类型
- 使用预处理器宏构造用于抛出 std::exception 的信息消息的简单方法
- std::exception::What()的目的是什么
- std::exception's what() 返回"std::exception"
- 私有继承自 std::runtime_error 的类不会被捕获为 std::exception