Catching and Handling 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. 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.

這節描述如何去使用三個異常處理器組件 - trycatchfinally blocks - 去寫一個異常處理器。然後將會解釋在Java SE 7中引入的try-with-resources語句。try-with-resources語句特別適合使用Closeable類型資源的情形,比如流。

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的類。當這個類的對象被構造時,它創建了一個包含了數值從0到9的ArrayList對象。這個類同樣定義了一個叫做writeList的方法,這個方法會將list中的數值寫入到一個叫做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 list;
    private static final int SIZE = 10;

    public ListOfNumbers () {
        list = new ArrayList(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)或是太大(超過ArrayList當前包含的元素數量),它將拋出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方法拋出的異常IndexOutOfBoundException是一個未檢查異常。

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類和其中哪些地方可能會被拋出異常,你已經準備好去寫異常處理器去捕獲和處理那些異常。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章