java中在finally语句中使用return语句

来源:互联网 发布:淘宝宝贝主图文字添加 编辑:程序博客网 时间:2024/06/06 15:52

当抛出异常时在finally中使用return语句
当一个程序段抛出异常的时候,如果在finally语句中使用了return语句,就会覆盖掉前面try语句中抛出的异常。导致上层方法不能捕获到调用这个方法抛出的异常。

/** * @author Mingming * @Description * @Date Created in 21:00 2017/11/16 * @Modificd By */public class Exception {    public static void main(String[] args){        Exception exception = new Exception();          try {             int number = exception.test();          }catch (java.lang.Exception e){              System.out.println("main catch Exception");          }    }    int test() throws java.lang.Exception{        try {            throw new java.lang.Exception();        }catch (java.lang.Exception e){            System.out.println("test catch Exception");            throw e;        }finally {            return 0;        }    }}

当在try语句中使用了return语句,然后又在finally中使用了return语句
finally语句中的return语句会覆盖掉前面的return语句

/** * @author Mingming * @Description * @Date Created in 21:00 2017/11/16 * @Modificd By */public class Exception {    public static void main(String[] args){        Exception exception = new Exception();          try {             int number = exception.test();              System.out.println(number);          }catch (java.lang.Exception e){              System.out.println("main catch Exception");          }    }    int test() throws java.lang.Exception{        try {            return 2;        }catch (java.lang.Exception e){            System.out.println("test catch Exception");            throw e;        }finally {            return 0;        }    }}
阅读全文
0 0
原创粉丝点击