Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try...catch vs if...else for exceptions - Java

What if I want to take user input from the args[0] array, but just in case I (the user) forgot to define it, I wanted a prompt to come up - is it better to use an if block to determine whether the array item(s) is empty or not, or to catch the exception? So, is this

public class Stuff {
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        String foo;
        if(args.length > 0) {
            foo = args[0];
        }
        else {
            foo = getString("Input? ");
        }
    }
    public static String getString(String prompt) {
        System.out.print(prompt + " ");
        String answer = input.nextLine();
        return answer;
    }   
}

better or worse than

public class Stuff {
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        String foo;
        try {
            foo = args[0];
        }
        catch(ArrayIndexOutOfBoundsException e) {
            foo = getString("Input? ");
        }
    }
    public static String getString(String prompt) {
        System.out.print(prompt + " ");
        String answer = input.nextLine();
        return answer;
    }   
}
like image 384
Bluefire Avatar asked Nov 30 '25 05:11

Bluefire


2 Answers

Your first example will still throw an exception since in the if statement you are still accessing an index which does not exist.

If you want to use an if statement then you should be checking that the length of the array is greater than the index you are trying to access for example:

if(args.length > 0)
    foo = args[0];
like image 100
Jon Taylor Avatar answered Dec 02 '25 17:12

Jon Taylor


You need to test args.length rather than reading args[0]

But apart from that error, it is better to use if/else for the following reasons:

  • It makes the code clearer
  • It has better performance (although not relevant in this case)
  • There is no exceptional condition (it is expected that the args array may be empty in some circumstances e.g. "user error", so the code should be able to handle it). Exception throwing should be reserved for exceptional situations that shouldn't happen.
like image 24
mikera Avatar answered Dec 02 '25 17:12

mikera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!