java在处理异常时finally语句的作用

先看代码:

public class text {
    public int devide(int x, int y) throws Exception {
        int result = x / y;
        return result;
    }
}

class TestException {
    public static void main(String[] args) {
        try {
            new text().devide(3, 1);
            return; // 在下图的运行结果中,第一个运行结果没有这条语句,第二个运行结果有这条语句
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println("finally");
        }
        System.out.println("program is running here!");
    }
}

 

运行结果:

这里写图片描述

从图中可以看出第一个运行结果有运行System.out.println(“program is running here!”);语句,第二个运行结果没有运行这条语句。因为第二条语句在try语句有return;语句,所以没有运行最后一条语句。但不管有没有return;语句运行了finally语句,这就是finally的作用。这个作用比喻:可在程序运行后关闭文件,不管运行结果如何都关闭文件,就可以用这一条语句。但可以用exit函数退出再不执行finally语句。比喻将return换成System.exit(0);就可以不执行

posted @ 2016-12-06 22:50  天涯海角路  阅读(339)  评论(0)    收藏  举报