如下所示:
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
結(jié)論: 如果沒有異常, 則執(zhí)行try 中的代碼塊,直到 try 中的 return,接著執(zhí)行 finally 中的代碼塊,finally 執(zhí)行完后 , 回到try 中執(zhí)行 return 。退出函數(shù)。
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
結(jié)論: 如果try 中有異常, 則在異常語句處,跳轉(zhuǎn)到catch 捕獲的異常代碼塊, 執(zhí)行完 catch 后,再執(zhí)行 finally ,跳出 try{}catch{}finally{} ,繼續(xù)向下執(zhí)行,不會去執(zhí)行try中 后面的語句。
以上這篇finally 一定會執(zhí)行(實例代碼)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答
圖片精選