Most of the time you will create exceptions just like that. At first it seems weird, but think about the semantics you want to pass.
It’s no different than you saying there was a Exception
and a BadFileFormat
? Even if internally these classes change nothing, the second is much more specific and informative. And as it is more specific it can be caught with greater granularity.
Of course it is likely that the text message that the exception usually has will also be customized. Often even if you pass some text when you launch the exception, the actual text is formed by this parameter and something else that already exists within the class.
You have to think about how much you want to have this granularity. It’s good to some extent. There are cases where it is better to put this detail within the exception itself. See database error exceptions, there is no exception for every possible error. The detail is within the class, possibly with properties that only this exception has. So there are cases where there are a lot more things written in the exception.
Eventually you can write a method that helps you recover from the exception, but I don’t see anyone doing it and I think it’s bad practice. My intuition says yes, but I have no basis to say.
But the most common is to add specific properties with relevant information. For example, an SQL error may have a ErrorCode
and ErrorMessage
(this is more specific than the general exception message. Think about the information that you can add (that is available) and that the code that captures the exception can use in some useful way, whether to decide what to do, or to present more user-oriented information or put in the log.
I often say that exception is not always the best mechanism, although the languages and frameworks and you end up having to adapt to it.
Has a my answer that shows when to create and throw exceptions, probably helps to understand this question.
Other relevant information before leaving making exception for everything.
Obs.: If the answer is yes, I will remove the question... :v
– KaduAmaral
Identify is one of the reasons, another could be pass parameters identifying exactly what happened, where, which objects involved, etc. But if none of this is necessary, better reuse one of the classes even ready (my opinion, do not take as fact).
– mgibsonbr