15

Do you think it is ok to use error codes within exception to specify error type? Please take a look on this code:

public class MyException extends Exception {
    public static final String ERROR_CODE_INVALID_NAME = "";
    public static final String ERROR_CODE_INVALID_ID = "";
    ...

    private String errorCode;

    public MyException(String message, String errorCode) {
        super(message);
        this.errorCode = errorCode;
    }

    public String getErrorCode() {
        return errorCode;
    }
}

I know that it is better to use enum instead of Strings in this example, but I'm actually concerned about the concept of error codes. Do you think exceptions hierarchy would be better here? I can't find any authoritative source that says error codes within exception is anti-pattern. Thx.

Nutella
  • 83
  • 8
Darkoboar
  • 195
  • 1
  • 1
  • 6
  • Looks like a duplicate of http://stackoverflow.com/questions/446663/best-way-to-define-error-codes-strings-in-java. – Alexander Pavlov Feb 15 '12 at 10:35
  • Thx, I saw this question, but there wasn't a discussion that this approach is generally wrong (except of one opinion in the very end). I wanted raise a discussion exactly in the way of correctness of such approach. – Darkoboar Feb 15 '12 at 10:41

5 Answers5

8

Error codes are useful when

  • you can't display a complete error message (dish washer display)
  • the code has to be processed internally (some logic is triggered if a certain code appears or a server sends an error code to the client while the client is responsible for the message)
  • we have a great manual and the user can use the code to get comprehensive information
  • The user does not need to know, what happend, but has to contact the vendor

So, most time, I don't see any added value in error codes. I prefer an exception hierarchy or at least clear error message that are really useful, when found in a logfile (even 2 years after the programmer has left the company).

If you have requirements for error codes - the solution is not bad. Consider collecting all error codes in a central repository (a properties file) so that you can exchange the complete set easily:

myexception.ERROR_CODE_INVALID_NAME=text or number
myexception.ERROR_CODE_INVALID_ID=text or number
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • As an addition to the list of useful cases: A relatively large amount of similar error cases (In my scenario >50 things that can go wrong during a mobile network operation). I don't see any value in providing 50 different exceptions, but the specific error has to somehow be communicated from the networking to the UI layer. – Jan Groth Jun 10 '14 at 05:33
4

From my experience exception codes are used mostly as information message for user.

I didn't saw even once that somebody try to parse general exception message in order to react differently depends on error code, usually it's done via exception hierarchy.

From another hand it could be hard to create new exception subclass for every particular case and then exception codes are used.
For example, if for user code it doesn't meter why transaction failed, it should rollback it any way, but for end user it's important why it happened (wrong params, database connection or else).

So, to summarize, if you'r expecting different ways to handle different situations it's better to use different exception types, but if you should handle few problems in the same way but only notify user about particular cause it's easier to use exception codes.

Rrr
  • 1,747
  • 3
  • 17
  • 22
3

I usually use a combination of both.

You need to categories your exceptions and make a design decision.

For example, you may use parameters such as source of exception, type, impact and handling to categorize your exception. If the exceptions fall in same category, use error codes within. Use hierarchy for the exception falling in different categories.

If you chose Exception Handling an important parameter, you may choose between the two options based on how you want to handle them:

  1. Use error codes if you want to catch all types in one catch block and handle them in a generic way.
  2. Use hierarchy if you want to catch specific type at a time and handle them accordingly.
Husain Basrawala
  • 1,757
  • 15
  • 21
2

Performance-wise creating a stacktrace of complex exception hierarchy is very expensive from both memory and time aspects, so if you create a complex custom exception hierarchy for something that you can solve by 3-4 static error codes... I would prefer the error code option. In general I prefer working with Runtime exceptions (not checked in method signature) the deffensive approach of catching checked exceptions is little out-dated IMO.

aviad
  • 8,229
  • 9
  • 50
  • 98
  • 4
    Creating an exception with an error code is neither faster nor less memory-intensive than creating an exception that has a large superclass hierarchy. While calling the constructor might yield a couple of nanoseconds improvement (because you’re calling three constructors less) you will need more memory because you are also storing an `int` (or `enum` or whatever). Most of the time is spent creating the stack trace so what I’m trying to say: premature optimization is the root of all evil. Apart from that it’s mostly a style question. :) – Bombe Feb 15 '12 at 12:04
  • @Bombe, agreed. creating a stacktrace will be the overhead and not the c'tor time. – aviad Feb 15 '12 at 13:04
1

If you want to react differently (in code) depending on what caused the exception (either invalid name or invalid id) then I would suggest having different exceptions.

If not, then you don't even need the getErrorCode() method, you can just add the error code to the message of the exception and the exception will give you all the information you need for debugging.

ughzan
  • 1,548
  • 1
  • 14
  • 24