我正在用 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/