简体   繁体   English

尝试... catch vs if ... else for exceptions - Java

[英]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? 如果我想从args[0]数组中获取用户输入怎么办,但是如果我(用户)忘了定义​​它,我想要提示 - 是否更好地使用if块来确定是否数组项是否为空,或者是否捕获异常? 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语句中您仍在访问不存在的索引。

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语句,则应检查数组的长度是否大于您尝试访问的索引,例如:

if(args.length > 0)
    foo = args[0];

IMO, if-else is better/faster in this case. IMO,if-else在这种情况下更好/更快。

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. 但正如乔恩泰勒所说,你的if语句不会那样。

You need to test args.length rather than reading args[0] 你需要测试args.length而不是读取args[0]

But apart from that error, it is better to use if/else for the following reasons: 但除了该错误之外,最好使用if/else ,原因如下:

  • 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). 没有异常情况(预计args数组在某些情况下可能为空,例如“用户错误”,因此代码应该能够处理它)。 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. 鉴于Jon Taylor所证明的更正,我更喜欢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. 不仅仅是速度增益(在你的例子中我认为不会引人注意),而是因为带有if的代码解释了它的意图,简化了代码的未来维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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