finally 一定会执行(实例代码)
如下所示:
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 一定会执行(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
应用启动数据初始化接口CommandLineRunner和Application详解
这篇文章主要介绍了应用启动数据初始化接口CommandLineRunner和Application详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-12-12
解决Idea报错There is not enough memory
在使用Idea开发过程中,可能会遇到因内存不足导致的闪退问题,出现"There is not enough memory to perform the requested operation"错误时,可以通过调整Idea的虚拟机选项来解决,方法是在Idea的Help菜单中选择Edit Custom VM Options2024-11-11
Spring Security实现禁止用户重复登陆的配置原理
这篇文章主要介绍了Spring Security实现禁止用户重复登陆的配置原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-12-12
SpringMVC事件监听ApplicationListener实例解析
这篇文章主要介绍了SpringMVC事件监听ApplicationListener实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-11-11


最新评论