Most of the time you will create exceptions anyway. At first it seems weird, but think about the semantics you want to go through.
Is not it quite different to say that there was a Exception
and a BadFileFormat
? Even though internally these classes do not change anything, the second is much more specific and informative. And being more specific can be captured with greater granularity .
Of course, it is likely that the text message that the exception usually has will also be customized. Many times even if you pass some text when you throw the exception, the actual text is formed by this parameter and something else already exists within the class.
You have to think how much you want to have this granularity. She is good up to a point. There are cases where it is best to place this detail within the exception itself. See the database error exceptions . There is no exception for every possible error. The breakdown is within the class, possibly with properties that only this exception has. So there are cases that there are a lot more things that are written in the exception.
Eventually you can write a method that helps you recover from the exception, but I do not see anyone doing this and I think it's a bad practice. My intuition says yes, but I have no basis to affirm.
But the most common is to add specific properties with relevant information. For example, a SQL error might have a ErrorCode
and ErrorMessage
(this is more specific than the general exception message.) Think about the information you can add (which is available) and that the code that catch the exception can use in some useful way, either to decide what to do, to present more information to the user or to put in log .
I often say that exception is not always the best mechanism , although the languages and frameworks today encourage him a lot and you end up having to adapt to it.
You have a answer of mine that shows when to create and throw exceptions , / p>
Another relevant information before exiting by making exceptions for everything .