Documentation

The Java™ Tutorials
Hide TOC
Specifying the Exceptions Thrown by a Method指定方法引发的异常
Trail: Essential Java Classes
Lesson: Exceptions

Specifying the Exceptions Thrown by a Method指定方法引发的异常

The previous section showed how to write an exception handler for the writeList method in the ListOfNumbers class.上一节演示了如何在ListOfNumbers类中为writeList方法编写异常处理程序。Sometimes, it's appropriate for code to catch exceptions that can occur within it.有时,代码捕捉可能发生在其中的异常是合适的。In other cases, however, it's better to let a method further up the call stack handle the exception.但是,在其他情况下,最好让调用堆栈更上层的方法处理异常。For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package.例如,如果将ListofNumber类作为类包的一部分提供,则可能无法预测包中所有用户的需求。In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it.在这种情况下,最好不要捕获异常,并允许调用堆栈更高的方法来处理它。

If the writeList method doesn't catch the checked exceptions that can occur within it, the writeList method must specify that it can throw these exceptions.如果writeList方法没有捕获其中可能发生的已检查异常,writeList方法必须指定它可以抛出这些异常。Let's modify the original writeList method to specify the exceptions it can throw instead of catching them.让我们修改原始writeList方法,以指定它可以抛出的异常,而不是捕获它们。To remind you, here's the original version of the writeList method that won't compile.为了提醒您,这里是writeList方法的原始版本,它不会编译。

public void writeList() {
    PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
    for (int i = 0; i < SIZE; i++) {
        out.println("Value at: " + i + " = " + list.get(i));
    }
    out.close();
}

To specify that writeList can throw two exceptions, add a throws clause to the method declaration for the writeList method.要指定writeList可以引发两个异常,请在writeList方法的方法声明中添加一个throws子句。The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method.throws子句包含throws关键字,后跟该方法引发的所有异常的逗号分隔列表。The clause goes after the method name and argument list and before the brace that defines the scope of the method; here's an example.子句位于方法名称和参数列表之后,位于定义方法范围的大括号之前;这里有一个例子。

public void writeList() throws IOException, IndexOutOfBoundsException {

Remember that IndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory.记住IndexOutOfBoundsException是一个未经检查的异常;将其包含在抛出条款中不是强制性的。You could just write the following.你可以写下面的内容。

public void writeList() throws IOException {

Previous page: Putting It All Together
Next page: How to Throw Exceptions