I’m asking this mainly about Java, but I guess it applies to a whole host of languages.
Consider,
if(myVariable==null){
doSomethingAboutIt();
}
else carryOn(myVariable);
and
try{
carryOn(MyVariable);
}
catch(NullPointerException e ){
doSOmethingAboutIt();
}
Are both these code blocks essentially the same? Is there any reason to choose the second approach? Of course, it would be better if myVariable was never null, but it seems that the best way to check for it is to do a simple if-statement.
From my stance, I’m hesitant to consider these two code blocks equivalent in intent. Sure, they go through the same error handling, but that’s a developer’s decision more than anything else.
To me, the
ifis testing to see if a value can be used, and if it can’t, it’s working around the issue. Thetry...catchblock is assuming the value is valid, and if it isn’t, it falls through to work around the aberrant behavior.Exceptions should primarly be considered when aberrant, program-breaking code occurs (divide-by-zero, etc).