felix fritz felix fritz - 6 months ago 11
Java Question

If-Else statements vs Exception-Catcher?

I got tired of adding seemingly endless if-else statements into my code, so I wondered if it would be better practice if I'd just catch Exceptions if something wasn't right. Eg. instead of saying:

public static boolean firstStringOfArrayIsTheSameAsTheWord(String word, String[] array) {
if(word != null) {
if(array.length > 0) {
return word.equalsIgnoreCase(array[0]);
}
}
return false;
}


I'd just have:

public static boolean firstStringOfArrayIsTheSameAsTheWord(String word, String[] array) {
try {
return word.equals(array[0]);
} catch(/*NullPointerException or an ArrayIndexOutOfBoundsException*/ Exception e) {
return false;
}
}


Note that I do know that I could use multiple arguments in the if-statements, but I'm just interested in what method would be better-to-use in practice and why.

Thanks in advance!

Answer

No, thats not a good idea, thats an abuse of Exception handling.

You are meant to avoid unnecesary exception catching, exceptions should only be used for things that go wrong because they are outside of your control and not as part of the normal program flow. Also, as @SJuan76 said you'll be hiding situations where there is a real Exception.

If you are tired of using if-else statements, you can try using a switch(which will even work for strings in Java 7) or improve polymorphism in your application.

Comments