文档

Java™ 教程
隐藏目录
将所有内容整合在一起
目录:基本的Java类
课程:异常
章节:捕获和处理异常

将所有内容整合起来

在异常处理程序执行完毕后,运行时系统将控制权传递给 finally 块。无论上面捕获的异常是什么,finally 块中的代码都会执行。在这种情况下,FileWriter 从未打开,因此不需要关闭。在 finally 块执行完毕后,程序会继续执行 finally 块后的第一条语句。

下面是当抛出 IOException 异常时 ListOfNumbers 程序的完整输出。

进入 try 语句块
捕获到 IOException: OutFile.txt
PrintWriter 未打开 

下面的代码清单中的粗体代码显示了在此情况下执行的语句:

public void writeList() {
   PrintWriter out = null;

    try {
        System.out.println("进入 try 语句块");
        out = new PrintWriter(new FileWriter("OutFile.txt"));
        for (int i = 0; i < SIZE; i++)
            out.println("索引为: " + i + " 的值 = " + list.get(i));
                               
    } catch (IndexOutOfBoundsException e) {
        System.err.println("捕获到 IndexOutOfBoundsException: "
                           + e.getMessage());
                                 
    } catch (IOException e) {
        System.err.println("捕获到 IOException: " + e.getMessage());
    } finally {
        if (out != null) {
            System.out.println("关闭 PrintWriter");
            out.close();
        } 
        else {
            System.out.println("PrintWriter 未打开");
        }
    }
}

情况2:try 块正常退出

在这种情况下,try 块范围内的所有语句都成功执行且没有抛出异常。执行会从 try 块末尾跳出,运行时系统会将控制权传递给 finally 块。由于一切都成功,当控制权到达 finally 块时,PrintWriter 是打开的,而 finally 块会关闭 PrintWriter。同样,在 finally 块执行完毕后,程序会继续执行 finally 块后的第一条语句。

下面是当没有抛出异常时 ListOfNumbers 程序的输出。

进入 try 语句块
关闭 PrintWriter

下面的示例中的粗体代码显示了在此情况下执行的语句。

public void writeList() {
    PrintWriter out = null;
    try {
        System.out.println("进入 try 语句块");
        out = new PrintWriter(new FileWriter("OutFile.txt"));
        for (int i = 0; i < SIZE; i++)
            out.println("索引为: " + i + " 的值 = " + list.get(i));
                  
    } catch (IndexOutOfBoundsException e) {
        System.err.println("捕获到 IndexOutOfBoundsException: "
                           + e.getMessage());

    } catch (IOException e) {
        System.err.println("捕获到 IOException: " + e.getMessage());
                                 
    } finally {
        if (out != null) {
            System.out.println("关闭 PrintWriter");
            out.close();
        } 
        else {
            System.out.println("PrintWriter 未打开");
        }
    }
}

上一页: 使用 try-with-resources 语句
下一页: 指定方法抛出的异常