博客專欄

EEPW首頁 > 博客 > 扣丁學(xué)堂Java培訓(xùn)之finally 一定會執(zhí)行(實例代碼)

扣丁學(xué)堂Java培訓(xùn)之finally 一定會執(zhí)行(實例代碼)

發(fā)布人:扣丁學(xué)堂1 時間:2021-01-11 來源:工程師 發(fā)布文章

本篇文章小編和大家分享一篇finally 一定會執(zhí)行(實例代碼),小編覺得對學(xué)習(xí)Java開發(fā)技術(shù)感興趣的小伙伴會有幫助,因此分享給小伙伴們,想要參加Java培訓(xùn)或者是對Java感興趣的小伙伴可以了解一下。

扣丁學(xué)堂Java在線教程之finally 一定會執(zhí)行(實例代碼)

如下所示:

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


結(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 occured
finnaly occured
0
mian b= 3


結(jié)論: 如果try 中有異常, 則在異常語句處,跳轉(zhuǎn)到catch 捕獲的異常代碼塊, 執(zhí)行完 catch 后,再執(zhí)行 finally ,跳出 try{}catch{}finally{} ,繼續(xù)向下執(zhí)行,不會去執(zhí)行try中 后面的語句。


以上就是小編給大家分享的finally 一定會執(zhí)行(實例代碼),想要了解更多內(nèi)容的小伙伴們可以登錄扣丁學(xué)堂官網(wǎng)查詢更多的內(nèi)容??鄱W(xué)堂Java在線學(xué)習(xí)是業(yè)內(nèi)知名的培訓(xùn)機構(gòu),扣丁學(xué)堂不僅有專業(yè)的老師和與時俱進(jìn)的課程體系,還有大量的Java在線教程供學(xué)員觀看學(xué)習(xí)。喜歡Java,想要學(xué)習(xí)Java開發(fā)的小伙伴們快快行動吧??鄱W(xué)堂java技術(shù)交流群:487098661。微信號:codingbb

*博客內(nèi)容為網(wǎng)友個人發(fā)布,僅代表博主個人觀點,如有侵權(quán)請聯(lián)系工作人員刪除。



關(guān)鍵詞:

相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉