I am writing a Windows application in C ++ and have encountered the following problem when dealing with exceptions.
I have a base exception class from which all other exceptions flow. In the base class, I have a method for reporting an error of any exception. Then this method returns an exception (via '* this').
Now the problem arises when I want to extend a derived exception, and later use it in a catch block. Since the extend method is declared in the base class, the catch block captures the base class instead of the derived class. Is there any way around this so that the correct derived class is found instead?
Here are some examples to illustrate the problem:
class BaseException {
BaseException() { }
Exception& extend( string message ) {
return *this;
}
}
class DerivedException : public BaseException {
DerivedException() : Exception() { }
}
int main() {
try {
...
try {
...
throw DerivedException( "message1" );
}
catch ( DerivedException& exc ) {
throw exc.extend( "message2" );
}
}
catch ( DerivedException& ) {
}
}
catch ( BaseException& ) {
}
}
"" , , . , .