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单点登陆视频教程
相关文章
相关标签/搜索