Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions and error codes in Java [closed]

Tags:

java

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?

like image 447
prashanthkvs Avatar asked Jul 30 '26 18:07

prashanthkvs


2 Answers

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:

  1. Catch the exception that determines the context of an error
    • Security
    • Database
    • Processing
    • Parsing
    • Invalid operation
  2. Check the exception code to determine the source
    • An user doesn't have enough privileges to do what he tried to do
    • Database connection errora
    • Query related issues
    • The system is currently overloaded
    • No managers found for a certain operation

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.

like image 103
Fritz Avatar answered Aug 01 '26 08:08

Fritz


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.

like image 25
xlecoustillier Avatar answered Aug 01 '26 07:08

xlecoustillier