简体   繁体   English

为什么以下Java代码无法编译?

[英]Why won't the following java code compile?

Quite Frankly, I'm just not understanding what my instructor is asking me to do here. 坦白说,我只是不明白我的老师要我在这里做什么。 I've tried using "try - catch" blocks, as well as throws Exception in the method signature. 我尝试使用“ try-catch”块,并在方法签名中引发Exception。 I've read about checked and unchecked exceptions. 我已经阅读了有关检查和未检查异常的信息。 I'm sure this will get voted down or closed, but can someone throw me a bone here? 我敢肯定这将被否决或关闭,但是有人可以在这里扔我一块骨头吗? My instructors instructions are as follows: 我的讲师说明如下:

"Correct it so it compiles." “更正它以便编译。”

class Exception3{
    public static void main(String[] args){         
    if (Integer.parseInt(args[0]) == 0)             
        throw new Exception("Invalid Command Line Argument");     
     } 
}

It's obvious that it is throwing a RuntimeException. 显然,它引发了RuntimeException。 More Specifically an ArrayIndexOutOfBoundsException. 更具体地说,是ArrayIndexOutOfBoundsException。 I know the cause of the exception is because the array is empty, so the referenced index doesn't exist. 我知道异常的原因是因为数组为空,所以引用的索引不存在。 I mean, technically I could just erase if(Integer.parseInt(args[0]) == 0) and throw new Exception("Invalid Command Line Argument"); 我的意思是,从技术上讲,我可以删除if(Integer.parseInt(args[0]) == 0)throw new Exception("Invalid Command Line Argument"); and replace it with System.out.println("It compiles now"); 并将其替换为System.out.println("It compiles now");

Any ideas? 有任何想法吗?

public static void main(String[] args) throws Exception{         
    if (Integer.parseInt(args[0]) == 0)             
        throw new Exception("Invalid Command Line Argument");     
     } 

Your method throwing Exception , so method declaration should specify that it may throw Exception . 您的方法抛出Exception ,因此方法声明应指定它可能抛出Exception

As per java tutorial 根据java教程

Checked exceptions are subject to the Catch or Specify Requirement. 已检查的异常受“捕获”或“指定要求”的约束。 All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. 除Error,RuntimeException及其子类指示的那些异常外,所有异常都是经过检查的异常。

You have to either catch it using a try catch statement: 您必须使用try catch语句来捕获它:

class Exception3 {
    public static void main(String[] args) {
        try {
            if (Integer.parseInt(args[0]) == 0)
                throw new Exception("Invalid Command Line Argument");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

or declare it at the method header: 或在方法标题处声明它:

class Exception3 {
    public static void main(String[] args) throws Exception {
        if (Integer.parseInt(args[0]) == 0)
            throw new Exception("Invalid Command Line Argument");
    }
}

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

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