关于Java中try catch finally throw return的执行顺序问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Java中try catch finally throw return的执行顺序问题相关的知识,希望对你有一定的参考价值。
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的执行顺序问题的主要内容,如果未能解决你的问题,请参考以下文章
关于Java里try/catch/finally/有return时执行过程
java中的“try - catch -finally”结构中的“finally”都有哪些用途