1

Possible Duplicate:
Exceptions or error codes
When is it appropriate to use error codes?

I'm wondering when we should use error codes as used in languages such as C and when to use exceptions. Consider the following example in which we need a getData() function which should return a string of data if successful and error messages otherwise. How should we report errors? as exceptions or error messages?

public int fo(arguments) {
    //some code
    String data = "";
    String errMsg = "";
    boolean rc = getData(arguments, data, errMsg);
    // do something based on the results of getData()
    // and report error messages in case of errors
}

What do you think about the following implementation:

boolean getData(some arguments, String data, String errorMessage){
    {
        //check arguments for null pointers or invalid values and return error
        //message
        errorMessage = "Invalid Arguments";
        return false;
    }
    {
        //check for other errors
        errorMessage = "Some Error";
        return false;
    }
    // no error, return valid data
    data = "some valid data";
    return true;
}

As far as I know we shouldn't use exceptions for flow control. Could you please comment on proper use of error codes and exceptions?

Community
  • 1
  • 1
ggcodes
  • 2,859
  • 6
  • 21
  • 34
  • `errorMessage = "Invalid Arguments"; return false;` ==> `throw new IllegalArgumentException("Invalid argument: data was null")` (for example) is what one would expect in such a situation. – assylias Dec 20 '12 at 00:13
  • Wanted to correct typo in title, but question with that title [already exists](http://stackoverflow.com/questions/253314/exceptions-or-error-codes) – mishadoff Dec 20 '12 at 00:16
  • For some reason some people think that Exceptions shouldn't be used here. I don't see why not. If you use an exception you can have your method return data **OR** throw an Exception that will contain the error message. Your current approach (which tries to return 3 pieces of data) will not work the way you have it. – jahroy Dec 20 '12 at 00:22

1 Answers1

4

First of all, your example wouldn't work, as arguments are passed by value in Java. So even though you change the value of errorMessage, that change won't be visible outside the method.

But assuming that you fix this and return the error code correctly, the question boils down to where you want to handle the error.

Exceptions automatically "bubble up" on the call stack, until they find a catch block that handles that particular type of exception. This gives you the opportunity to deal with them on a much higher level, whereas if you return an error code, you have to deal with that error code straight away in the immediate caller (which then might set another error code for its caller and so on, when you see this pattern, you can be certain that you should've thrown an exception instead)

biziclop
  • 48,926
  • 12
  • 77
  • 104