一,
package demo; public class tryDemo { private static int see(){ int s = 0; try{ s +=2; System.out.println("执行完try"); return s; }catch(Exception e){ return s+1; }finally{ System.out.println("执行完finally"); } } public static void main(String[] args) { int a = see(); System.out.println("a : "+ a ); } }
运行结果:
执行完try
执行完finally
a : 2
说明,如果 try当中有return 的话, 先执行完return中的语句,在执行finally中的语句,最后 返回 try 中的 return。
二,如果 finally当中也有 return呢 ?
package demo; public class tryDemo { private static int see(){ int s = 0; try{ s +=2; System.out.println("执行完try"); return s; }catch(Exception e){ return s+1; }finally{ System.out.println("执行完finally"); return s+3; } } public static void main(String[] args) { int a = see(); System.out.println("a : "+ a ); } }
输出结果:
执行完try
执行完finally
a : 5
说明: 这种情况下,不执行 try当中的 return ,最后返回的是 finally 中的值 。
三 ,
如果 try当中有 return s,
finally没有 return, 但在 finally 中 有 对 s 的操作,那么 try 当中的 return s 是 更改后的 s 吗?
package demo; public class tryDemo { private static int see(){ int s = 0; try{ s +=2; System.out.println("执行完try"); return s; }catch(Exception e){ return s+1; }finally{ System.out.println("执行完finally"); s +=1; //s=5; } } public static void main(String[] args) { int a = see(); System.out.println("a : "+ a ); } }
输出结果:
执行完try
执行完finally
a : 2
说明, finally当中的 对 s 的修改 并不对 try当中的 return 值产生影响。
try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?
原文:https://www.cnblogs.com/william-dai/p/13322071.html