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:
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?
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
.
About your options, ask yourself if
null
)?null
return 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With