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語句體繼續執行後續代碼。