博客專欄

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

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

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

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

扣丁學(xué)堂Java在線教程之finally 一定會(huì)執(zhí)行(實(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);
 }
}


輸出:

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í)行,不會(huì)去執(zhí)行try中 后面的語句。


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

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



關(guān)鍵詞:

相關(guān)推薦

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

關(guān)閉