Skip to content
Reyes Yang edited this page Dec 28, 2019 · 1 revision

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:

想要创建一个异常处理器,首先需要将可能抛出异常的代码放到一个 try 语句块中。一般情况下,一个 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. (The catch and finally blocks are explained in the next two subsections.)

上面例子中标记为 code 的代码片段,可以包含一行或多行可能抛出异常的代码。(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. 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. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.

为了给 ListOfNumbers 类的 writeList 方法创建一个异常处理器,需要把抛出异常的 writeList 方法放到一个 try 代码块中。有不至一种方法可以达到这个目的。又可以将每一行可能抛出异常的代码放到它自己的 try 代码块中,并且分别为他们提供异常处理器。或者,你可以将 writeList 方法的所有代码都放到一个 try 代码块中并提供相关的多个异常处理器。下面演示了如何将整个方法放到一个 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. 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 代码块中发生了异常,异常会被关联的异常处理处理。为了给 try 代码块关联一个异常处理器,我们必须在它后面添加一个 catch 代码块;在下一节,The catch Blocks 中,将会看看如何做。