欢迎来到工商注册核名查询系统!

Java编程

当前位置:主页 > 软件编程 > Java编程 >

finally 一定会执行(实例代码)

来源:本站原创|时间:2022-11-25|栏目:Java编程|

如下所示:

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

结论: 如果没有异常, 则执行try 中的代码块,直到 try 中的 return,接着执行 finally 中的代码块,finally 执行完后 , 回到try 中执行 return 。退出函数。

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

结论: 如果try 中有异常, 则在异常语句处,跳转到catch 捕获的异常代码块, 执行完 catch 后,再执行 finally ,跳出 try{}catch{}finally{} ,继续向下执行,不会去执行try中 后面的语句。

以上这篇finally 一定会执行(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

更多Java编程

您可能感兴趣的文章

阅读排行

本栏相关

随机阅读

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 工商注册核名查询系统 版权所有