c++ - 返回基类类型的引用时捕获派生异常?

标签 c++ polymorphism

我正在用 C++ 编写 Windows 应用程序,在处理异常时遇到以下问题。

我有一个异常基类,所有其他异常都从中派生。在基类中,我有一个方法来处理任何异常的错误消息。然后该方法返回异常(通过“*this”)。

现在,当我想扩展派生异常并稍后在 catch block 中使用它时,问题就出现了。由于 extend 方法是在基类中声明的,因此 catch block 捕获基类而不是派生类。有什么方法可以解决这个问题,以便捕获正确的派生类吗?

下面是一些说明问题的代码:


// DECLARATIONS

class BaseException {
    BaseException() { }

    Exception& extend( string message ) {
        // extend message

        return *this;
    }
}

class DerivedException : public BaseException {
    DerivedException() : Exception() { }
}



// RUNNING CODE

int main() {
    try {
         ...

         try {
             ...

             // Something goes wrong
             throw DerivedException( "message1" );
         }
         catch ( DerivedException& exc ) {
             throw exc.extend( "message2" );
         }
    }
    catch ( DerivedException& ) {
        // Here is where I *want* to land
    }
    }
    catch ( BaseException& ) {
        // Here is where I *do* land
    }
}

目前我已经“解决”了它,方法是不是使扩展方法成为虚拟方法,而是在每个异常中声明它并返回正确的类型。它有效,但并不漂亮。

最佳答案

extend() 调用和异常的重新抛出分开会简单得多:

 catch ( DerivedException& exc ) {
     exc.extend( "message2" );
     throw;
 }

这样 extend() 就不必返回任何东西,并且总是会抛出/捕获正确的异常。

关于c++ - 返回基类类型的引用时捕获派生异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531956/

相关文章:

c++ - 解决由于类之间的循环依赖而导致的构建错误

python - pip install uwsgi 失败/usr/local/include/string/string.h :7:10: fatal error: 'sstream' file not found?

c++ - 一个数字,因为它是质数部分

javascript - 多态参数javascript

c# - 未导出成员函数时从 C# 调用 C++ native /非托管成员函数

C++ 线程安全 - 在 worker 和 controller 之间交换数据

c++ - 指向成员变量的多态指针

c# - 虚拟调用与类型检查的另一个例子

c++ - 继承和内联?

java - 无多态性的接口(interface)