繁体   English   中英

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

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

坦白说,我只是不明白我的老师要我在这里做什么。 我尝试使用“ try-catch”块,并在方法签名中引发Exception。 我已经阅读了有关检查和未检查异常的信息。 我敢肯定这将被否决或关闭,但是有人可以在这里扔我一块骨头吗? 我的讲师说明如下:

“更正它以便编译。”

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

显然,它引发了RuntimeException。 更具体地说,是ArrayIndexOutOfBoundsException。 我知道异常的原因是因为数组为空,所以引用的索引不存在。 我的意思是,从技术上讲,我可以删除if(Integer.parseInt(args[0]) == 0)throw new Exception("Invalid Command Line Argument"); 并将其替换为System.out.println("It compiles now");

有任何想法吗?

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

您的方法抛出Exception ,因此方法声明应指定它可能抛出Exception

根据java教程

已检查的异常受“捕获”或“指定要求”的约束。 除Error,RuntimeException及其子类指示的那些异常外,所有异常都是经过检查的异常。

您必须使用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();
        }
    }
}

或在方法标题处声明它:

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