首页 > 代码库 > 关于Java中try catch finally throw return的执行顺序问题
关于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的执行顺序问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。