We have a hierarchy of exception classes - there's a GenericException
class and a number of classes that derive from it. GenericException
is polymorphic - it has a virtual destructor.
One of derived classes is FileException
thrown to indicate errors when manipulating with filesystem objects. FileException
has GetErrorCode()
method that returns the code indicating what actually went wrong.
The hierarchy is already there, I can't change it, so it's out of the question.
Exceptions are thrown from code we don't control and they are always thrown with new keyword so we can only catch them by pointer - this is out of the question either.
Now I have a situation when a set of statements can generate an exception which is guaranteed to be derived from a GenericException
. If it is a FileException
and the type of error situation is "file not found" I want to do nothing, otherwise I want to show an error message and then I consider the exception handled anyway.
I have two options - either:
} catch( GenericException* e ) {
FileException* fileException = dynamic_cast<FileException*>( e );
if( fileException == 0 || fileException->GetErrorCode() != FileNotFound ) {
ShowMessage( e );
}
delete e;
}
or this one:
} catch( FileException* e ) {
if( fileException->GetErrorCode() != FileNotFound ) {
ShowMessage( e );
}
delete e;
} catch( GenericException* e ) {
ShowMessage( e );
delete e;
}
I prefer the first one because it reduces code duplication. But I've heard an opinion that since C++ allows for selective catch blocks (like in the second option) I should not use dynamic_cast
- selective catch blocks make no need for it.
Which option is better? What might be the reason to not the first option here?