finally语句是在try的return语句执行之后,return返回之前执行。
其实看一下你那个类的class字节码文件就知道了。 return的时候是复制了一个变量然后返回,所以之后finally操作的变量如果是基本类型的话不会影响返回值。 但是如果返回值是引用类型的话,因为指向同一个对象所以还是有影响的。
/** * @author lijinnan * @date:2014-1-22 */ public class FinallyTest { public static void main(String[] args) { System.out.println(test()); System.out.println(testPrimitive()); } public static Student test() { Student result = new Student("Tom", 0); try { result.setAge(1); return result; } catch (Exception e) { result.setAge(2); return result; } finally { result.setAge(3); //引用类型的返回值,可被修改 // return new Student("Kobe", 33); //可以被“具体值”覆盖 } } public static int testPrimitive() { int x = 0; try { x = 1; // int a=1/0; return x; } catch (Exception e) { x = 2; return x; } finally { x = 3; //基本类型的返回值,不可被修改 // return x; //可以被“具体值”覆盖 } } private static class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } public void setAge(int age) { this.age = age; } } }