我正在用C++编写一个Windows应用程序,在处理异常时遇到了以下问题.
我有一个基本异常类,所有其他异常都来自该类.在基类中,我有一个任何异常的错误消息的方法.然后该方法返回异常(通过'*this').
现在,当我想扩展派生异常并稍后在catch块中使用它时,会出现问题.由于extend方法是在基类中声明的,因此catch块捕获基类而不是派生类.有没有办法解决这个问题,以便找到正确的派生类?
以下是一些说明问题的代码:
// 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方法设为virtual来"解决"它,而是在每个异常中使用正确的返回类型声明它.它有效,但它并不漂亮.
分离extend()调用和重新抛出异常会简单得多:
catch ( DerivedException& exc ) {
exc.extend( "message2" );
throw;
}
Run Code Online (Sandbox Code Playgroud)
这种方式extend()不必返回任何内容,并始终抛出/捕获正确的异常.