天天看点

关于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