try catch finally执行顺序 (return / 变量覆盖)

finally有return 始终返回finally中的return 抛弃 try 与catch中的return

情况1:try{} catch(){}finally{} return x;

try{} catch(){}finally{} return x;
1 ->	2	->	3	->	4

情况2:try{ return x; }catch(){} finally{} return y;

try{ return x; }catch(){} finally{} return y;
try -> x计算[临时栈存]->finally ->return x的结果

情况3:try{ } catch(){return x;} finally{} return y;

try -> catch ->异常catch住 -> x计算[临时栈存]-> finally -> return x的结果;
无异常 -> finally -> return y;

情况4:try{ return x; }catch(){} finally{return y;}

try -> x计算[临时栈存] ->finally ->return y

情况5:try{} catch(){return x;}finally{return y;}

try -> catch捕获 -> x计算[临时栈存] ->finally ->return y

情况6:try{ return x;}catch(){return z;} finally{return y;}

try->x计算[临时栈存]->异常catch捕获-> z计算[临时栈存]->finally->return y;
无异常 -> finally -> return y;

eg1:finally无返回

int x = 1; try{x++; return x;} finally{++x;}
x = 2 ;

x计算后的值不会被finally改变
进入finally会提前栈保存return x 计算的值

try x:2
finally x:3
return x :2 == try x:2

finally无返回

eg2:finally带返回

int x = 1; try{x++; return x;} finally{++x; return x;}
x = 3 ;

x计算后的值不会被finally改变
进入finally会提前栈保存return x 计算的值
但是直接返回finally计算完成已经被影响的x值

try x:2
finally x:3
return x :3 == finally x:3

finally带返回

posted @ 2019-05-20 11:46  Zzzang  阅读(422)  评论(0编辑  收藏  举报