Reputation: 462
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!
Upvotes: 1
Views: 433
Reputation: 7076
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.
Upvotes: 6
Reputation: 11
The exception approach is not a good idea. Throwing an exception 1. it is slow 2. makes your application unreadable. As @greedybuddha said "use exceptions for exceptional events, never for control flow".
Upvotes: 0
Reputation: 47729
do {
if (conditionA) {
something;
}
else {
break;
}
if (conditionB) {
somethingElse;
}
else {
break;
}
...
} while(false);
Upvotes: 0
Reputation: 24885
First, IIRC correctly exception handling is slow. Not terribly slow, but nothing that you want to use in the mainstream logic.
Second, by working that way, you will be hiding the situations where there is a real Exception. Your user will try to load a file, but will only find that the file was not loaded, would not get any idea if the file was not found, the data was corrupt, whatever. You lose a lot of information.
If you want to make your code simpler, it would be better to do something like
/**
* ....
* @param word String must not be null.
* @param array String[] must not be null, have length at least 1, an array[0] must not be null
*/
public static boolean firstStringOfArrayIsTheSameAsTheWord(String word, String[] array) {
return word.equals(array[0]);
}
At least you delegate the responsability for sanitizing the parameters to the code that uses your method. Not a sensible thing to do (it goes against defensive programming) and your coworker will hate working with your code, but better than your first approach.
Upvotes: 3
Reputation: 7507
The general rule is, "use exceptions for exceptional events, never for control flow".
So use the if(...) else ...
please.
Upvotes: 4