简体   繁体   English

为什么会抛出异常?

[英]Why is exception thrown here?

I am preparing for OCA exams and read a lot, so today I saw an a question. 我正在准备OCA考试并阅读很多,所以今天我看到了一个问题。 Here is a code: 这是一个代码:

public class Fork {
  public static void main(String[] args) {
    if (args.length == 1 | args[1].equals("test")) {
        System.out.println("Test case");
    } else {
        System.out.println("production " + args[0]);
    }
  }     
}

And the command-line invocation: 和命令行调用:

java Fork live2

I thought that answer would be "production java" but the answer is "An exception is thrown at runtime" . 我认为答案是"production java"但答案是"An exception is thrown at runtime" Why is that? 这是为什么? we are providing values for args right? 我们正在为args提供价值吗? Can some one please explain me what is going on? 有人可以解释一下发生了什么事吗? Thanks! 谢谢!

In java Fork live2 there's only 1 command line argument - live2 . java Fork live2 ,只有一个命令行参数 - live2

args.length == 1 | args[1].equals("test") args.length == 1 | args[1].equals("test") is an OR operator that doesn't short circuit, which means both operands are guaranteed to be evaluated ( || is the OR operator that short circuits and only evaluates the right operand if the left operand is false), so if you supply a single command line argument as you did in java Fork live2 , args[1].equals("test") would still be evaluated and throw an ArrayIndexOutOfBoundsException exception. args.length == 1 | args[1].equals("test")是一个OR运算符,它不会短路,这意味着两个操作数都可以保证被评估( ||是OR运算符,它短路并且只评估右操作数,如果左边操作数是假的,所以如果你提供一个命令行参数就像你在java Fork live2args[1].equals("test")仍然会被计算并抛出一个ArrayIndexOutOfBoundsException异常。

If you change your condition to 如果你改变你的病情

if (args.length == 1 || args[1].equals("test"))

you'll get Test case printed, since args.length == 1 would be true and args[1].equals("test") won't be evaluated. 你将打印Test case ,因为args.length == 1将为true,并且不会评估args[1].equals("test")

in your if statement: 在你的if语句中:

args[1].equals("test")

you have only one argument, so args[1] throw array out of bound 你只有一个参数,所以args [1]将数组抛出界限

Instead of using | 而不是使用| , use || ,使用|| and instead of using args[1].equals("test") use args[0].equals("test") . 而不是使用args[1].equals("test")使用args[0].equals("test")

In the end it should look something like this: 最后看起来应该是这样的:

public class Fork {
  public static void main(String[] args) {
    if (args.length == 1 || args[0].equals("test")) {
        System.out.println("Test case");
    } else {
        System.out.println("production " + args[0]);
    }
  }     
}

You are giving only one command line argument. 您只提供一个命令行参数。 So while checking for args 1 , you are getting ArrayIndexOutOfBound Exception.. If you give two arguments, it will work perfectly.. 因此,在检查args 1时 ,您将获得ArrayIndexOutOfBound Exception ..如果您提供两个参数,它将完美地工作.. 我的输出

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

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