总结:java
一、无论有没有异常,finally中的代码都会执行
二、当try、catch中有return时,finally中的代码依然会继续执行
三、finally是在return后面的表达式运算以后执行的,此时并无返回运算以后的值,而是把值保存起来,无论finally对该值作任何的改变,返回的值都不会改变,依然返回保存起来的值。也就是说方法的返回值是在finally运算以前就肯定了的。
四、若是return的数据是引用数据类型,而在finally中对该引用数据类型的属性值的改变起做用,try中的return语句返回的就是在finally中改变后的该属性的值。
五、finally代码中最好不要包含return,程序会提早退出,也就是说返回的值不是try或catch中的值测试
先执行try中的语句,包括return后面的表达式,
有异常时,先执行catch中的语句,包括return后面的表达式,
而后执行finally中的语句,若是finally里面有return语句,会提早退出,
最后执行try中的return,有异常时执行catch中的return。指针
在执行try、catch中的return以前必定会执行finally中的代码(若是finally存在),若是finally中有return语句,就会直接执行finally中的return方法,因此finally中的return语句必定会被执行的。编译器把finally中的return语句标识为一个warning.
code
参考代码:TryCatchTest对象
// 当try、catch中有return时,finally中的代码会执行么? public class TryCatchTest { public static void main(String[] args) { // System.out.println("return的返回值:" + test()); // System.out.println("包含异常return的返回值:" + testWithException()); System.out.println("return的返回值:" + testWithObject().age); // 测试返回值类型是对象时 } // finally是在return后面的表达式运算以后执行的,此时并无返回运算以后的值 //,而是把值保存起来,无论finally对该值作任何的改变,返回的值都不会改变,依然返回保存起来的值。 //也就是说方法的返回值是在finally运算以前就肯定了的。 static int test() { int x = 1; try { return x++; } catch(Exception e){ }finally { System.out.println("finally:" + x); ++x; System.out.println("++x:" + x); // finally代码中最好不要包含return,程序会提早退出, // 也就是说返回的值不是try或catch中的值 // return x; } return x; } static int testWithException(){ Integer x = null; try { x.intValue(); // 造个空指针异常 return x++; } catch(Exception e){ System.out.println("catch:" + x); x = 1; return x; // 返回1 // return ++x; // 返回2 }finally { x = 1; System.out.println("finally:" + x); ++x; System.out.println("++x:" + x); // finally代码中最好不要包含return,程序会提早退出, // 也就是说返回的值不是try或catch中的值 // return x; } } static Num testWithObject() { Num num = new Num(); try { return num; } catch(Exception e){ }finally { num.age++; // 改变了引用对象的值 System.out.println("finally:" + num.age); } return num; } static class Num{ public int age; } }