finally:一般用于资源释放,断开连接,关闭管道流等
一般搭配try -- catch --finally 或者 try --- finally
一般来说无论try中是否抛出异常,都会执行finally。
如果finally没有执行,有以下几种可能:
1. 没有进入try
2.try中发生死循环或者死锁
3.try中system.exit()
public static void main(String[] args) { int result = finallyNotWork(); System.out.println(result);// 10001 } public static int finallyNotWork() { int temp = 10000; try { throw new Exception(); } catch (Exception e) { return ++temp; } finally { temp = 99990; } }finally是在return后执行的,finally执行完后,再把return中保存的值返回
public class TryCatchFinally { static int x = 1; static int y = 10; static int z = 100; public static void main(String[] args) { int value = finallyReturn(); System.out.println("value=" + value); System.out.println("x=" + x); System.out.println("y=" + y); System.out.println("z=" + z); } private static int finallyReturn() { try { // ... return ++x; } catch (Exception e) { return ++y; } finally { return ++z; } } }进了try return中保存的值是2,执行finally后,return中保存的值是101;
所以value是101,x=2,y没有进入catch所以没有变化为10,z为101;
finally语句中有return会让返回值变得不可预测,所以一般在finally中做释放资源的操作,如断开连接,关闭流等操作。
Class Test{ public static String output=""; public static void foo(int i){ try{ if(i==1){ throw new Exception(); } output+="1"; } catch(Exception e){ output+="2"; return; } finally{ output+="3"; } output+="4"; } public static void main(String args[]){ foo(0); System.out.println(output);//134 foo(1); System.out.println(output);//13423 } }f(0)时,没有抛出异常执行try中+”1“,finally中+”3“,后续代码+”4“ 134
f(1)时,有异常抛出,try下面语句不执行,直接执行catch语句+”2“,再执行finally中+“4”,后续代码不执行。13423



