Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw an exception or return null

If I've got the function below, with two choices

private MyObject findBlank() {
    for (int i = 0; i < pieces.length; i++) {
        if(pieces[i].isBlank()){
            return pieces[i];
        }
    }
    return null;
}

private MyObject findBlank() {
    for (int i = 0; i < pieces.length; i++) {
        if(pieces[i].isBlank()){
            return pieces[i];
        }
    }
    throw new NoSuchFieldError("No blank piece found!");
}

From this method I know that it should always return an object one of the 'pieces' always is isBlank() == true , the return null at the end is just to please the compiler. Since this is the case and my code wouldn't work anyway if it returned null, is this the correct please to throw an exception?

My options are:

  1. return null and the app will get a NullPointerException in some edge case
  2. return null and wrap the use of the method with (myObject != null) checks
  3. throw an exception which will blow it up at runtime

I guess what I'm asking is, is this the correct place to throw an exception? i.e. there is nothing I can do about it if it gets into the situation. Is this classed as 'exceptional' or should I null check what my method returns (which makes my code look horrible). If I know it shouldn't return null then I should throw the exception right?

Also how would I choose what exception, or extend one and throw my own?

like image 825
Blundell Avatar asked Jun 03 '12 19:06

Blundell


2 Answers

I guess what I'm asking is, is this the correct place to throw an exception?

If it were an exceptional situation, then yes. If the possibility of not finding anything that matches the criteria is expected then the situation is not exceptional and you should return null.

like image 92
K-ballo Avatar answered Nov 02 '22 22:11

K-ballo


About your options, ask yourself if

  1. Is it a good idea to have your program blow up at some point after this method returned an unexpected value (i.e. null)?
  2. What exactly will be hidden if you mask out the null return value?
  3. Is it a good idea to blow up immediately, just because there was a wrong value?

Personally I'd go for option 2 or 3, depending on whether I like the answer to question 2 or 3 better. Option 1 definitely is a bad idea, especially if it's not supposed to happen. If the program throws a NPE way after your function returned, you'll have a hard time figuring out where the null came from. Especially if it happens months after you finished working on this particular function.

If you choose to throw an exception, you immediately see where something went wrong and you can directly go there to figure out why it went wrong. Returning null and checking for it in the calling function could also work, but only if you don't fail silently, but actually do something to handle the problem properly.

like image 34
Wormbo Avatar answered Nov 03 '22 00:11

Wormbo