天天看點

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

<code>try</code> <code>{</code>

<code>    </code> 

<code>    </code><code>normal statement;     </code><code>//1.</code>

<code>    </code><code>exception occurred;   </code><code>//2.</code>

<code>    </code><code>return</code> <code>"try"</code><code>;</code>

<code>} </code><code>catch</code> <code>(Exception ex) {</code>

<code>    </code><code>normal statement;     </code><code>//3.</code>

<code>    </code><code>return</code> <code>"catch"</code><code>;</code>

<code>} </code><code>finally</code> <code>{</code>

<code>    </code><code>normal statement;     </code><code>//4.</code>

<code>    </code><code>return</code> <code>"finally"</code><code>;     </code><code>//5. --&gt;End</code>

<code>}</code>

<code>    </code><code>return</code> <code>"catch"</code><code>;       </code><code>//5. --&gt;End</code>

<code>    </code><code>throw</code> <code>Exception;</code>

<code>    </code><code>throw</code> <code>Exception;      </code><code>//5. --&gt;End</code>

結論:

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=&gt;finally,則回溯到catch中執行return/throw;如果是try=&gt;finally,則回溯到try中執行return/throw;如果try/catch中都不存在return/throw,則跳出try-catch-finally語句體繼續執行後續代碼。

本文轉自 rickqin 51CTO部落格,原文連結:http://blog.51cto.com/rickqin/1868754