I’m writing a windows application in C++ and encountered the following problem when working with exceptions.
I have a base exception class from which all other exceptions derive from. In the base class I have a method for the error message of any exception. That method then returns the exception (through ‘*this’).
Now, the problem occurs when I want to extend a derived exception and later user it in a catch block. Since the extend method is declared in the base class, the catch block catches the base class instead of the derived class. Is there any way of working around this so that the correct derived class is caught instead?
Here are some code illustrating the problem:
// 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
}
}
At the moment I have “solved” it by not making the extend method virtual, but declaring it in each exception with correct return type. It works, but it’s not pretty.
It would be much simpler to separate the
extend()call and the re-throwing of the exception:This way
extend()doesn’t have to return anything and always the right exceptions are thrown/caught.