异常捕获try-catch-finally

来源:互联网 发布:学生管理系统java界面 编辑:程序博客网 时间:2024/05/22 08:29

1、在异常捕获处理时,通常使用:

    try{            System.out.println(x/0);//可能出现异常的语句        }catch(ArithmeticException e){                                    //出现算术异常时处理语句        }finally{        }

finally中的语句为必须要执行的语句。

没有出现异常时,执行try语句后,执行finally语句,如下:

public static void main(String[] args) {        System.out.println(method());    }private static int method() {        int x = 3;        try{            x = x/1;        }catch(ArithmeticException e){            return x;        }finally{            System.out.println("执行finally");            x++;        }        System.out.println("finally执行完毕");        return x;    }

输出:
->执行finally
->finally执行完毕
->4

解析:函数没有发生异常,因此只走了try和finally语句,没有走catch语句。所以先打印出“执行finally”,再打印出“x++”后的值:4;


在catch到异常时,执行catch中语句,然后执行finally语句,如下:

public static void main(String[] args) {        System.out.println(method());    }private static int method() {        int x = 3;        try{            x = x/0;//注意,此处分母变为0        }catch(ArithmeticException e){            return x;        }finally{            System.out.println("执行finally");            x++;        }        System.out.println("finally执行完毕");        return x;    }

输出:
->执行finally
->3

解析:函数发生算术运算异常,走了try和catch、finally语句,按照常规逻辑,在catch中遇到return,就会结束函数,返回3的,这里为什么不是这样呢?其实,走到catch里面遇到return时,打了一个返回标记,同时标记了此时的x的值,然后继续把finally执行完(反正,不管什么情况,finally都要执行),输出“执行finally”,执行x++,然后回到标记处执行返回语句,所以返回的仍然是当时的3,而不是4;


2、那么,如果没有写finally程序块儿,对try-catch的运行会有影响吗?答案是不会。毕竟finally是必须要执行的,写了就要执行,不写那就不执行,至于对前面的语句,没有影响。

public static void main(String[] args) {        System.out.println(method());    }private static int method() {        int x = 3;        try{            x = x/0;//注意,此处分母变为0        }catch(ArithmeticException e){            return x;        }        x++;        System.out.println("finally执行完毕");        return x;    }

输出:
->3


解析:catch到异常后,标记return语句,继续执行,但是后面没有finally语句,那就返回标记处执行标记的return和标记时的x的值,catch后的语句不执行。

3、那么,问题又来了,如果没有写catch程序块儿呢?结果会是怎么样呢,如下:

public static void main(String[] args) {        System.out.println(method());    }private static int method() {        int x = 3;        try{            x = x/0;//注意,此处分母变为0        }finally{            System.out.println("执行finally");            x++;        }        System.out.println("finally执行完毕");        return x;    }

输出:
->执行finally
->Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.sunwoda.io.TryCatchDemo.method5(TryCatchDemo.java:74)
at com.sunwoda.io.TryCatchDemo.main(TryCatchDemo.java:13)
丛上看出,程序执行到try时,出现了异常,但是仍然将finally执行完毕后,将异常信息打印出来。

finally 执行遇到一种情况例外,即如果finally前执行System.exit(0);那么就会退出虚拟机,不再执行finally语句。

0 0