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 first step in constructing an exception handler is to enclose the code that might throw an exception within a 构造异常处理程序的第一步是在try
block.try
块中包含可能引发异常的代码。In general, a 通常,try
block looks like the following:try
块如下所示:
try { code } catch and finally blocks . . .
The segment in the example labeled 示例中标记为code
contains one or more legal lines of code that could throw an exception.code
的段包含一行或多行可能引发异常的合法代码。(The (在接下来的两小节中,将解释catch
and finally
blocks are explained in the next two subsections.)catch
块和finally
块。)
To construct an exception handler for the 要从writeList
method from the ListOfNumbers
class, enclose the exception-throwing statements of the writeList
method within a try
block.ListOfNumbers
类为writeList
方法构造异常处理程序,请将writeList
方法的异常引发语句包含在try
块中。There is more than one way to do this.实现这一点的方法不止一种。You can put each line of code that might throw an exception within its own 您可以将可能引发异常的每一行代码放在它自己的try
block and provide separate exception handlers for each.try
块中,并为每一行代码提供单独的异常处理程序。Or, you can put all the 或者,您可以将所有writeList
code within a single try
block and associate multiple handlers with it.writeList
代码放在一个try
块中,并将多个处理程序与之关联。The following listing uses one 下面的清单对整个方法使用了一个try
block for the entire method because the code in question is very short.try
块,因为所讨论的代码非常短。
private List<Integer> list; private static final int SIZE = 10; public void writeList() { PrintWriter out = null; try { System.out.println("Entered try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + list.get(i)); } } catch and finally blocks . . . }
If an exception occurs within the 如果try
block, that exception is handled by an exception handler associated with it.try
块中发生异常,则该异常由与其关联的异常处理程序处理。To associate an exception handler with a 要将异常处理程序与try
block, you must put a catch
block after it; the next section, The catch Blocks, shows you how.try
块关联,必须在其后面放置catch
块;下一节,catch块,向您展示了如何使用它。