finally 必定會執行(實例代碼)

以下所示:html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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);
  }
}

輸出:java

?
1
2
3
try ……
finnaly occured
mian b= 2

結論: 若是沒有異常, 則執行try 中的代碼塊,直到 try 中的 return,接着執行 finally 中的代碼塊,finally 執行完後 , 回到try 中執行 return 。退出函數。程序員

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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);
  }
}

輸出:面試

?
1
2
3
4
ArithmeticException occured
finnaly occured
0
mian b= 3

結論: 若是try 中有異常, 則在異常語句處,跳轉到catch 捕獲的異常代碼塊, 執行完 catch 後,再執行 finally ,跳出 try{}catch{}finally{} ,繼續向下執行,不會去執行try中 後面的語句。算法

 

 

 
全套javaSE大牛畢經之路基礎+進階+實戰(價值476元)
2017最新視頻全套javaSE視頻教程(小白程序員入門教程)視頻+課堂筆記+源碼)
JAVA開發之大型互聯網企業級分佈式通訊 RMI及JMS學習以及深刻講解 attach_img
基於SOA 思想下的WebService多層架構入門到精通(課件+源碼)
JAVA開發之大型互聯網企業高併發架構Tomcat服務器性能優化  ...2
Activiti工做流框架從入門到大神企業開發實例講解與OA項目實戰視頻課程
JAVA架構師系列課程分佈式緩存技術Redis權威指南
JAVA架構師系列之消息中間件RocketMQ入門視頻課程
Java Web整合開發實戰:基於Struts 2+Hibernate+Spring(課件+源碼+視頻)
JAVA架構師系列之消息中間件RocketMQ入門視頻課程
Spring Cloud 系列學習視頻教程附課件全套
Java Web整合開發實戰:基於Struts 2+Hibernate+Spring(課件+源碼+視頻)
[JAVA] 2017最新 Java,C++面試算法與數據結構全套視頻教程
[JAVA] 編寫高質量java代碼:改善Java程序的151個建議
Java 校招面試,Google 面試官親授–某課網價值248元實戰教程 attach_img
Spring Security開發安全的REST服務–某課網價值366元實戰教程 attach_img  ...2
Spring Boot從入門到實戰 基礎實戰系列教程全集 attach_img
國內第一套關於Nutch相關框架講解的視頻教程 20講Nutch培訓視頻教程 與Hadoop相關
一頭扎進SpringBoot視頻教程
SSO之CAS單點登陸視頻教程
相關文章
相關標籤/搜索