简体   繁体   中英

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;
    }   
}

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];

IMO, if-else is better/faster in this case.

Throwing an exception is used when you are inside a method and you want to say to the caller that something went wrong, and you can't do it with the return value.

But as said Jon Taylor, your if statement won't work that way.

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 eg "user error", so the code should be able to handle it). Exception throwing should be reserved for exceptional situations that shouldn't happen .

您真正需要的只是一行代码。

final String foo = args.length > 0? args[0] : getString("Input? ");

使用if块来检查数组是否为空是容易且快速的。

Given the correction evidenced by Jon Taylor, I will prefer the version with if.

Not only for the speed gain (that in your example I guess will be not noticeable), but because the code with the if better explains its intents, simplifying future maintenance on the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM