catch和处理异常
本节描述如何使用三个异常处理程序组件try
,catch
和finally
块来编写异常处理程序。然后,说明在 Java SE 7 中引入的try-
with-resources 语句。 try-
with-resources 语句特别适合于使用Closeable
资源的情况,例如流。
本节的最后一部分将通过一个示例,并分析各种情况下发生的情况。
以下示例定义并实现了一个名为ListOfNumbers
的类。构造后,ListOfNumbers
将创建一个ArrayList
,该ArrayList
包含 10 个Integer
元素,其 Sequences 值为 0 到 9.ListOfNumbers
类还定义了一个名为writeList
的方法,该方法将数字列表写入名为OutFile.txt
的文本文件中。本示例使用在java.io
中定义的输出类,在Basic 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();
}
}
黑体字的第一行是对构造函数的调用。构造函数初始化文件上的输出流。如果无法打开文件,则构造函数将抛出IOException
。第二行粗体是对ArrayList
类的get
方法的调用,如果其参数的值太小(小于 0)或太大(大于ArrayList
当前包含的元素数),则抛出IndexOutOfBoundsException
。
如果您try编译ListOfNumbers类,则编译器会打印一条有关FileWriter
构造函数引发的异常的错误消息。但是,它不会显示有关get
引发的异常的错误消息。原因是由构造函数IOException
引发的异常是已检查的异常,而由get
方法IndexOutOfBoundsException
引发的异常是未检查的异常。
既然您已经熟悉ListOfNumbers
类以及可以在其中引发异常的位置,那么您就可以编写异常处理程序来catch和处理这些异常了。