finally
一定会执行return
以最后一次为准return
后的finally
是否修改了数据,得看具体类型
try{} catch(){}finally{} return
按照正常的顺序执行:有错会执行catch
,finally
都会执行,最后执行return
。
private static int returnInFinally_00(){
int a ;
try {
System.out.println("try...");
a = 3 / 0;
} catch (Exception e){
System.out.println("catch...");
} finally {
System.out.println("finally...");
a = 2;
}
return 100;
}
// 100
try{ return; }catch(){} finally{} return
try
中已经return
,所以不再执行finally
后面的return
。
private static int returnInFinally_01(){
int a ;
try{
System.out.println("try...");
a = 3 / 1;
return a;
} catch (Exception e){
System.out.println("catch...");
} finally {
System.out.println("finally...");
a = 2;
}
return 100;
}
// 3
try{ } catch(){return;} finally{} return
与上述情况类似
private static int returnInFinally_02(){
int a = 0;
try{
System.out.println("try...");
a = 3 / 0;
} catch (Exception e){
System.out.println("catch...");
return a;
} finally {
System.out.println("finally...");
a = 2;
}
return a;
}
// 0
try{ return; }catch(){} finally{return;}
程序执行try
块中return
之前(包括return
语句中的表达式运算)代码;再执行finally
块,因为finally
块中有return
所以提前退出(这提前退出的意思是指:后面的代码都不会再执行了,所以就退出)。
private static int returnInFinally_03(){
int a ;
try{
System.out.println("try...");
a = 3 / 1;
return a;
} catch (Exception e){
System.out.println("catch...");
} finally {
System.out.println("finally...");
a = 2;
return a;
}
//return 100; 不可能执行此代码,编译器直接报错
}
// 2
try{} catch(){return;}finally{return;}
与上述类似
private static int returnInFinally_04(){
int a = 0;
try{
System.out.println("try...");
a = 3 / 0;
} catch (Exception e){
System.out.println("catch...");
return a ++;
} finally {
System.out.println("finally...");
a ++;
return a;
}
}
// 2
try{ return;}catch(){return;} finally{return;}
同上述类似
private static int returnInFinally_05(){
int a = 1;
try{
System.out.println("try...");
a = 3 / 0;
return a;
} catch (Exception e){
System.out.println("catch...");
return a ++;
} finally {
System.out.println("finally...");
a ++;
return a;
}
}
// 3
return后在finally中修改值是否会影响结果?
问题回到传值还是传引用上啦,这里有疑问就再回去看看传值与传引用吧
// 一个普通测试类
private static class TestObject{
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
// 覆盖toString
@Override
public String toString() {
return "x = " + x;
}
}
private static TestObject returnInFinally_06(){
TestObject to = new TestObject();
try{
System.out.println("try...");
to.setX(1);// 设为1
return to;
} catch (Exception e){
System.out.println("catch...");
to.setX(2);// 设为2
return to;
} finally {
System.out.println("finally...");
to.setX(3);// 最终设为3
}
}
// try...
// finally...
// x = 3