Documentation

The Java™ Tutorials
Hide TOC
Catching and Handling Exceptions捕获和处理异常
Trail: Essential Java Classes
Lesson: Exceptions

Catching and Handling Exceptions捕获和处理异常

This section describes how to use the three exception handler components — the try, catch, and finally blocks — to write an exception handler.本节介绍如何使用三个异常处理程序组件—trycatchfinally块—编写异常处理程序。Then, the try-with-resources statement, introduced in Java SE 7, is explained.然后,解释了Java SE 7中引入的try-with-resources语句。The try-with-resources statement is particularly suited to situations that use Closeable resources, such as streams.try-with-resources语句特别适合于使用可关闭资源(如流)的情况。

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.下面的示例定义并实现了一个名为ListOfNumber的类。When constructed, ListOfNumbers creates an ArrayList that contains 10 Integer elements with sequential values 0 through 9.构造时,ListOfNumbers会创建一个ArrayList,其中包含10个连续值为0到9的整数元素。The ListOfNumbers class also defines a method named writeList, which writes the list of numbers into a text file called OutFile.txt.ListOfNumbers类还定义了一个名为writeList的方法,该方法将数字列表写入名为OutFile.txt的文本文件中。This example uses output classes defined in java.io, which are covered in Basic I/O.本例使用java.io中定义的输出类,这些类在基本输入输出中有介绍。

// 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.如果无法打开文件,构造函数将抛出IOExceptionThe 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).第二条粗体线是对ArrayList类的get方法的调用,如果其参数值太小(小于0)或太大(大于ArrayList当前包含的元素数),则会引发IndexOutOfBoundsException

If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor.如果尝试编译ListOfNumbers类,编译器将打印一条关于FileWriter构造函数引发的异常的错误消息。However, it does not display an error message about the exception thrown by get.但是,它不会显示有关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.原因是构造函数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类以及可以在其中抛出异常的位置,现在可以编写异常处理程序来捕获和处理这些异常了。


Previous page: The Catch or Specify Requirement
Next page: The try Block