java--18--异常处理

来源:互联网 发布:怎么查自己的淘宝密码 编辑:程序博客网 时间:2024/06/05 00:14

1 异常处理执行顺序
当出现异常时,异常处理各部分执行顺序

/**     * 测试异常处理各个位置执行情况     */    public static void TextException(){        try{            Integer a=1,b=0;            System.out.println("1:"+a/b);            return;        }catch(Exception e){            System.out.println("2:");            return;        }finally{            System.out.println("3:");            return;        }    }

执行结果:
这里写图片描述

/**     * 测试异常处理各个位置执行情况     */    public static Integer TextException_02(){        try{            Integer a=1,b=0;            System.out.println("1:"+a/b);            return 1;        }catch(Exception e){            System.out.println("2:");            return 2;        }finally{            System.out.println("3:");            return 3;        }    }

执行结果:
这里写图片描述

/**     * 测试异常处理各个位置执行情况     */    public static Integer TextException_02(){        try{            Integer a=1,b=0;            System.out.println("1:"+a/b);            return 1;        }catch(Exception e){            System.out.println("2:");            return 2;        }finally{            System.out.println("3:");//          return 3;        }    }

执行结果:
这里写图片描述
由执行结果可知:
不管catch中进行了何种处理,finally中均会被执行。如果catch中和finally中均有return语句,则catch中的return无效,返回的是catch中的return,但是如果只有catch中有return,那么将返回的是catch中的return,而finally中的语句正常执行,最后执行catch中的return。

0 0
原创粉丝点击