1

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!

felix fritz
  • 462
  • 2
  • 5
  • 21
  • You're apt to start another religious war (except that the last one is still on-going). But another "cheater" way to handle it is to put everything in a `do { ... } while(false)` block and then use `break` statements to leave the block. – Hot Licks May 17 '13 at 00:14
  • 2
    One way to make methods like this more readable (less ugly) is to do one `if` at a time and return immediately if your condition is not met. **If you keep your methods simple enough** you shouldn't run into a situation where your if/else ladder seems "_endless_". – jahroy May 17 '13 at 00:16
  • @jahroy That seems like a wonderful solution, thanks a lot! I'll use that in the future. – felix fritz May 17 '13 at 00:38

5 Answers5

6

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.

Community
  • 1
  • 1
0x6C38
  • 6,796
  • 4
  • 35
  • 47
4

The general rule is, "use exceptions for exceptional events, never for control flow".

So use the if(...) else ... please.

greedybuddha
  • 7,488
  • 3
  • 36
  • 50
3

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.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • So besides that it's slow, it's probably also not a good idea to catch multiple exceptions, just in case there's something else is going on, eg. } catch(NullPointerException e) { } catch(ArrayIndexOutOfBoundsException e) { } catch(Exception e) { //Okay, now something went really wrong }, right? – felix fritz May 17 '13 at 00:24
  • You could do something like that and it would be 'correct', but would not save you any typing, would be slower, and your code would be more difficult to read. – SJuan76 May 17 '13 at 00:27
0
do {
    if (conditionA) {
        something;
    }
    else {
        break;
    }
    if (conditionB) {
        somethingElse;
    }
    else {
        break;
    }
    ...
} while(false);
Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • Oh wow, I've never thought about those statements. So what's your opinion? Does the do-while loop make if-statements faster or is it against every programmer's religion? :D – felix fritz May 17 '13 at 00:32
  • It's probably fairly cheap, and a good optimizer won't be choked by it. Confusing to the uninitiated, and some pitfalls since it's basically using GOTOs (which, as we all know, are [considered harmful](http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html)). – Hot Licks May 17 '13 at 01:16
0

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".

Luke Tong
  • 11
  • 1