關於Java中try catch finally throw return的執行順序問題

來源:互聯網
上載者:User

標籤:try catch finally return throw   順序   

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

關於Java中try catch finally throw return的執行順序問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.