Skip to content

Catching and Handling Exceptions

Reyes Yang edited this page Dec 28, 2019 · 3 revisions

This section describes how to use the three exception handler components — the try, catch, and finally blocks — to write an exception handler. Then, the try-with-resources statement, introduced in Java SE 7, is explained. The try-with-resources statement is particularly suited to situations that use Closeable resources, such as streams.

本节将介绍如何使用三个异常处理关键字 - try, catch 和 finally - 来写异常 handler。然后,会解释从 Java SE 7 引入的 try-with-resource 语句。try-with-resource 语句特别适用于使用了 Closeable 资源的场景,例如 stremas。

The last part of this section walks through an example and analyzes what occurs during various scenarios.

最后一节会通过分析一个例子,来详细解释各个情况下都发生了什么。

The following example defines and implements a class named ListOfNumbers. When constructed, ListOfNumbers creates an ArrayList that contains 10 Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList, which writes the list of numbers into a text file called OutFile.txt. This example uses output classes defined in java.io, which are covered in Basic I/O.

下面的例子实现了一个名为 ListOfNumbers 的类。每当创建成功后,ListOfNumbers 会创建一个 ArrayList,其中含有从 0 到 9 的十个整数。ListOfNumber 类同时也定义了一个 writeList 的方法,它会将整数列表写道一个名为 OutFile.txt 的文本文件中。这个列子使用的输出类定义在 java.io 包中,涵盖了基本的 I/O 操作。

// Note: This class will not compile yet.
import java.io.*;
import java.util.List;
import java.util.ArrayList;

public class ListOfNumbers {

    private List<Integer> list;
    private static final int SIZE = 10;

    public ListOfNumbers () {
        list = new ArrayList<Integer>(SIZE);
        for (int i = 0; i < SIZE; i++) {
            list.add(new Integer(i));
        }
    }

    public void writeList() {
	// The FileWriter constructor throws IOException, which must be caught.
        PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));

        for (int i = 0; i < SIZE; i++) {
            // The get(int) method throws IndexOutOfBoundsException, which must be caught.
            out.println("Value at: " + i + " = " + list.get(i));
        }
        out.close();
    }
}

The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an IOException. The second boldface line is a call to the ArrayList class's get method, which throws an IndexOutOfBoundsException if the value of its argument is too small (less than 0) or too large (more than the number of elements currently contained by the ArrayList).

第一行加粗代码调用了构造函数。构造函数初始化了一个文件的输出流。如果文件不能打开,构造函数会抛出一个 IOException。第二行加粗代码调用了 ArrayList 类的 get 方法,当方法的参数太小(小于0)或者太大(大于数组中的元素个数时),会抛出一个 IndexOutOfBoundsException。

If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor. However, it does not display an error message about the exception thrown by get. The reason is that the exception thrown by the constructor, IOException, is a checked exception, and the one thrown by the get method, IndexOutOfBoundsException, is an unchecked exception.

如果一尝试编译这个 ListOfNumbers 类,编译器会打印出一个错误信息,关于 FileWriter 构造函数抛出的异常。但是,它不会展示过于 get 方法抛出异常的错误信息。原因是构造函数抛出的 IOException 是一个受检异常,而 get 方法抛出的 IndexOutOfBoundsException 是一个非受检异常。

Now that you're familiar with the ListOfNumbers class and where the exceptions can be thrown within it, you're ready to write exception handlers to catch and handle those exceptions.

到这里你应该已经熟悉了 ListOfNumbers 类以及它里面会抛出异常的代码,下面你将使用异常 handlers 来捕获以及处理这些异常。