public class TestEx {
public static void main(String[] args) {
System.out.println(tEX());
System.out.println(tEx(new StringBuffer()));
}
static int tEX() {
int a = 1;
try{
a = 2;
throw new NumberFormatException();
}catch(Exception e) {
a ++;
return a;
}finally {
a = 4;
}
}
static StringBuffer tEx(StringBuffer bs) {
String s = "a";
try {
bs.append(s);
throw new NumberFormatException();
}catch(Exception e) {
return bs;
}finally {
bs.append("c");
}
}
}
运行结果:
3
ac
总结:1、若返回类型基本数据类型,先将值存放起来,然后执行finally里面的代码,若此时对返回值有所改变,并不影响将要返回的值,但代码块依旧会执行。
2、若finally里面有return,则会覆盖掉原来的return。
3、若返回值是一个对象引用,则finally代码块中的代码会对返回的对象产生影响