I have a query regarding error handling in java. Suppose for a library there are several error codes. Is it a good practice to have a single exception and include an enum of error codes in side that, for various errors ?
Update: Is it a good practice to have error codes within an exception?
An error and an error code are two separate things. One defines what happened and the other one identifies the particular source of the error.
The best example of this are DB related exceptions, where a SQL exception includes a code defining the tipe of error that caused it.
Making that code accessible through an enumeration or a field is a design decision. If you have one exception to throw and you add an error code to it, it can be taken as a two-step exception handling:
Once you determined the source (code) and you know its context (exception), you can act accordingly. IMHO, a hierarchy is a good approach that can be extended with a code when needed. Just keep in mind that there's an impact in maintainability and complexity if you go as far as to subclass an exception 10 times just to represent the source.
Not really. You should use different Exception types, one for each error type (within reasonable limits, don't create hundreds of different exception types!).
It allows you to catch only those you really want to catch, instead of processing each exception to discover what happened.
However, feel free to customize exception message to clarify the source of the error inside several exceptions of the same type.
This simple explanation is clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With