c++ - 异常中的虚方法

标签 c++ exception

我已经创建了我自己的异常类,它派生自 runtime_error 并在 c'tor 中获取一个 int。

我想为这个异常创建一个基类,以便使用多态性,所以我只能捕获基类,基本上我会捕获派生类,然后从中调用 .what() 方法。

所以,这是基类:(ofc 在另一个 cpp 文件中我得到了 baseException::~baseException(){})

class baseException
{
    virtual ~baseException()=0 {}
    virtual const char* what()=0;
};

这是派生类:

class myException: public runtime_error, public baseException
{
public:
    myException(int): runtime_error("Error occured") {}
    const char* what() {return runtime_error::what();}
};

但是当我主要写的时候:

catch(baseException* x)
{
cout<<x->what();
}

它只是跳过它而不进入 block ,即使 myException 继承自 baseException。有什么建议吗?

最佳答案

您应该通过引用(或 const 引用)捕获异常,而不是通过指针。

关于c++ - 异常中的虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11083421/

相关文章:

java - 有什么理由抛出 'Exception' 并立即捕获它吗?

c++ - 如何在 32 位和 64 位环境中使用 intptr_t 可靠地专门化模板?

delphi - 尝试加载库时出现 AccessViolation 异常

c++ - 理解 z 缓冲区格式 direct x

c++ - llvm 文档示例无法编译

c# - MySql + Entity Framework = 每个派生表必须有自己的别名

c# - 在 ASP.NET WebService 上捕获 WebMethod 抛出的自定义异常

java - api中的异常处理

c++ - 信号未在此范围内声明/未定义对 class::method 的引用

c++ - 使用 gdb 调试共享库