It is a common pattern I see where the error codes associated with an exception are stored as Static final ints. when the exception is created to be thrown, it is constructed with one of these codes along with an error message.
This results in the method that is going to catch it having to look at the code and then decide on a course of action.
The alternative seems to be- declare a class for EVERY exception error case (although related exceptions would derieve from a common base class )
Is there a middle ground ? what is the recommended method ?
This is a good question. I believe there is definitely a middle ground.
Error codes are essential in my opinion for displaying errors to QA, and for customers to report to customer support and back to developers.
For programmatically handling errors I personally don’t recommend error codes, I’d recommend a new Class for each category of errors, but definitely not for every single error. Java did a decent job getting us started with Exceptions like IOException, IllegalArgumentException, UnsupportedOperationException, etc. I frequently throw and catch these when appropriate in my code.
If you have a new category of exceptions that your code should respond to programmatically then you should definitely create a new class for it, extending the appropriate parent class. For example UserRegistrationException or ProductException.