1

坦率地说,我只是不明白我的导师要我在这里做什么。我尝试过使用“try-catch”块,以及在方法签名中抛出异常。我已经阅读过检查和未经检查的异常。我敢肯定这会被否决或关闭,但是有人可以在这里给我扔一根骨头吗?我的导师指导如下:

“更正它以便编译。”

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");

有任何想法吗?

4

2 回答 2

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

你的方法抛出Exception,所以方法声明应该指定它可能会抛出Exception

按照java教程

已检查的异常受 Catch 或 Specify Requirement 的约束。除了 Error、RuntimeException 及其子类所指示的异常之外,所有异常都是已检查异常。

于 2012-11-13T04:20:25.447 回答
3

您必须使用 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");
    }
}
于 2012-11-13T04:28:11.993 回答