The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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 {