finally 一定会执行(实例代码)
2019/7/7 19:29:50
本文主要是介绍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 一定会执行(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持找一找教程网。
这篇关于finally 一定会执行(实例代码)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?