try {
normal statement; //1.
exception occurred; //2.
return "try";
} catch (Exception ex) {
normal statement; //3.
return "catch";
} finally {
normal statement; //4.
return "finally"; //5. -->End
}
try { normal statement; //1. exception occurred; //2. return "try"; } catch (Exception ex) { normal statement; //3. return "catch"; //5. -->End } finally { normal statement; //4. }
try { normal statement; //1. exception occurred; //2. return "try"; } catch (Exception ex) { normal statement; //3. throw Exception; } finally { normal statement; //4. return "finally"; //5. -->End }
try { normal statement; //1. exception occurred; //2. return "try"; } catch (Exception ex) { normal statement; //3. throw Exception; } finally { normal statement; //4. throw Exception; //5. -->End }
try { normal statement; //1. exception occurred; //2. return "try"; } catch (Exception ex) { normal statement; //3. throw Exception; //5. -->End } finally { normal statement; //4. }
结论:
1、Try-catch-finally中的finally一定会执行,而且,一定优先于try/catch中的return/throw语句执行,除非系统崩了或者程序使用System.exit(0)强行终止;
2、finally中如果有return或throw,则优先处理finally中的return/throw;
3、return和throw,从语句流转的角度上看,这两个语句是等效的;
4、finally中没有return或throw,则程序会回溯到try/catch中执行return/throw语句。如果当初是catch=>finally,则回溯到catch中执行return/throw;如果是try=>finally,则回溯到try中执行return/throw;如果try/catch中都不存在return/throw,则跳出try-catch-finally语句体继续执行后续代码。
本文出自 “BitterJava” 博客,请务必保留此出处http://rickqin.blog.51cto.com/1096449/1868754