扣丁學堂Java培訓之finally 一定會執行(實例代碼)
本篇文章小編和大家分享一篇finally 一定會執行(實例代碼),小編覺得對學習Java開發技術感興趣的小伙伴會有幫助,因此分享給小伙伴們,想要參加Java培訓或者是對Java感興趣的小伙伴可以了解一下。
如下所示:
class Exc{ int a; int b; } public class Except { @SuppressWarnings("finally") static int compute (){ Exc e = new Exc(); e.a = 10; e.b = 10; int res = 0 ; try{ res = e.a / e.b; System.out.println("try ……"); return res + 1; }catch(NullPointerException e1){ System.out.println("NullPointerException occured"); }catch(ArithmeticException e1){ System.out.println("ArithmeticException occured"); }catch(Exception e3){ System.out.println("Exception occured"); }finally{ System.out.println("finnaly occured"); } System.out.println(res); return res+3; } public static void main(String[] args){ int b = compute(); System.out.println("mian b= "+b); } }
輸出:
try …… finnaly occured mian b= 2
結論: 如果沒有異常, 則執行try 中的代碼塊,直到 try 中的 return,接著執行 finally 中的代碼塊,finally 執行完后 , 回到try 中執行 return 。退出函數。
class Exc{ int a; int b; } public class Except { @SuppressWarnings("finally") static int compute (){ Exc e = new Exc(); // e.a = 10; // e.b = 10; int res = 0 ; try{ res = e.a / e.b; System.out.println("try ……"); return res + 1; }catch(NullPointerException e1){ System.out.println("NullPointerException occured"); }catch(ArithmeticException e1){ System.out.println("ArithmeticException occured"); }catch(Exception e3){ System.out.println("Exception occured"); }finally{ System.out.println("finnaly occured"); } System.out.println(res); return res+3; } public static void main(String[] args){ int b = compute(); System.out.println("mian b= "+b); } }
輸出:
ArithmeticException occured finnaly occured 0 mian b= 3
結論: 如果try 中有異常, 則在異常語句處,跳轉到catch 捕獲的異常代碼塊, 執行完 catch 后,再執行 finally ,跳出 try{}catch{}finally{} ,繼續向下執行,不會去執行try中 后面的語句。
以上就是小編給大家分享的finally 一定會執行(實例代碼),想要了解更多內容的小伙伴們可以登錄扣丁學堂官網查詢更多的內容。扣丁學堂Java在線學習是業內知名的培訓機構,扣丁學堂不僅有專業的老師和與時俱進的課程體系,還有大量的Java在線教程供學員觀看學習。喜歡Java,想要學習Java開發的小伙伴們快快行動吧??鄱W堂java技術交流群:487098661。微信號:codingbb
*博客內容為網友個人發布,僅代表博主個人觀點,如有侵權請聯系工作人員刪除。