如下所示:
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 occuredmian 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 occuredfinnaly occured0mian b= 3
結論: 如果try 中有異常, 則在異常語句處,跳轉到catch 捕獲的異常代碼塊, 執行完 catch 后,再執行 finally ,跳出 try{}catch{}finally{} ,繼續向下執行,不會去執行try中 后面的語句。
以上這篇finally 一定會執行(實例代碼)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答