try-catch-finally的字节码原理

news/2025/3/13 22:35:13/

Java 中有一个非常重要的内容是 try-catch-finally 的执行顺序和返回值问题,其中 finally 一定会执行,但是为什么会这样? 下面看下 try-catch-finally 背后的实现原理

try-catch

public class Test {public static void main(String[] args) {foo();}public static void foo() {try {int i = 1 / 0;}catch (Exception e){System.out.println("执行异常");e.printStackTrace();}}}

字节码

public class com.yxzapp.Test {public com.yxzapp.Test();Code:0: aload_01: invokespecial #1                  // Method java/lang/Object."<init>":()V4: returnpublic static void main(java.lang.String[]);Code:0: invokestatic  #2                  // Method foo:()V3: returnpublic static void foo();Code:0: iconst_1                         // 将int 类型值1压栈到栈顶1: iconst_0						   // 将int 类型值0压栈到栈顶2: idiv                             // 将栈顶两int型数值相除并将结果压入栈顶3: istore_0                         // 将栈顶类型int数据存储到局部变量表下标04: goto          20                 // 如果不抛异常跳到20行7: astore_0                         // 将引入对象(异常对象)存储局部变量表下标08: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;11: ldc           #5                  // String 鎵ц寮傚父13: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V16: aload_017: invokevirtual #7                  // Method java/lang/Exception.printStackTrace:()V20: returnException table:from    to  target type0     4     7   Class java/lang/Exception
}

17 4: goto 20 // 如果不抛异常跳到20行

如果有异常抛出,如何处理呢?

当方法包含 try-catch 语句时,在编译单元生成的方法的 Code 属性中会生成一个异常表 (Exception table), 每个异常项表示一个异常处理器, 由 from 指针 、to 指针、target 指针 、所捕获的异常类型 type 四部分组成。这些指针的值是字节码索引,用于定位字节码。其含义是在 [from ,to) 字节码范围内,如果跑出来异常类型为 type 的异常,就会跳转到 target 指针表示的字节码处继续执行。

上面的例子中 Exception table表示,在 0 - 4 之间(不包含4),如果抛出类型为 Exception 或其子类就跳转到7继续执行

当抛出异常时,Java 虚拟机会自动将异常对象加载到操作数栈栈顶

多try-catch

public class Test {public static void main(String[] args) {foo();}public static void foo() {try {int i = 1 / 0;}catch (ArithmeticException e){System.out.println("执行异常 ArithmeticException");e.printStackTrace();} catch (NullPointerException e){System.out.println("执行异常 NullPointerException");e.printStackTrace();}}}

字节码

public class com.yxzapp.Test {public com.yxzapp.Test();Code:0: aload_01: invokespecial #1                  // Method java/lang/Object."<init>":()V4: returnpublic static void main(java.lang.String[]);Code:0: invokestatic  #2                  // Method foo:()V3: returnpublic static void foo();Code:0: iconst_11: iconst_02: idiv3: istore_04: goto          367: astore_08: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;11: ldc           #5                  // String 鎵ц寮傚父 ArithmeticException13: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V16: aload_017: invokevirtual #7                  // Method java/lang/ArithmeticException.printStackTrace:()V20: goto          3623: astore_024: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;27: ldc           #9                  // String 鎵ц寮傚父 NullPointerException29: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V32: aload_033: invokevirtual #10                 // Method java/lang/NullPointerException.printStackTrace:()V36: returnException table:from    to  target type0     4     7   Class java/lang/ArithmeticException0     4    23   Class java/lang/NullPointerException
}

可以看到 ,多一个 catcha 语句处理分析, 异常表里面就会多一条记录,当程序出现异常时, Java 虚拟机会从上至下遍历异常表中所有的条目。当触发异常的字节码索引值在某个条目的 [from 、to)范围内,则会判断抛出的异常是否是想捕获的异常或子类

如果异常匹配, Java 虚拟机将控制跳转到 target 指向的字节码继续执行;如果不匹配,则继续遍历异常表。如果遍历完所有的异常表还未找到匹配的异常处理器,那么该异常将继续抛到调用方 (caller)中重复上述的操作

try-catch-finally

public class Test {public static void main(String[] args) {foo();}public static void foo() {try {int i = 1 / 0;}catch (ArithmeticException e){System.out.println("执行异常 ArithmeticException");e.printStackTrace();} finally {System.out.println("执行");}}}

字节码

public class com.yxzapp.Test {public com.yxzapp.Test();Code:0: aload_01: invokespecial #1                  // Method java/lang/Object."<init>":()V4: returnpublic static void main(java.lang.String[]);Code:0: invokestatic  #2                  // Method foo:()V3: returnpublic static void foo();Code:0: iconst_1                          // 将int 类型值1压栈到栈顶1: iconst_0                          // 将int 类型值0压栈到栈顶2: idiv                              // 将栈顶两int型数值相除并将结果压入栈顶3: istore_0							// 开始执行 finally 代码块4: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;7: ldc           #4                  // String 鎵ц9: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V12: goto          5015: astore_0// 异常(被catch)情况下开始执行 finally 代码块16: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;19: ldc           #7                  // String 鎵ц寮傚父 ArithmeticException21: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V24: aload_025: invokevirtual #8                  // Method java/lang/ArithmeticException.printStackTrace:()V28: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;31: ldc           #4                  // String 鎵ц33: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V36: goto          5039: astore_1// 异常(catch中执行出现异常)代码块出现异常 情况下开始									   执行 finally 代码块40: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;43: ldc           #4                  // String 鎵ц45: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V48: aload_149: athrow50: returnException table:from    to  target type0     4    15   Class java/lang/ArithmeticException0     4    39   any15    28    39   any
}

可以看出字节码中 出现三次调用

   getstatic     #3                     // Field java/lang/System.out:Ljava/io/PrintStream;ldc           #4                        // String 鎵цinvokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V

都是在程序正常 return 和异常 throw 之前,其中两处在 try-catch 语句调用 return 之前,一处是在异常抛出 throw 之前

由代码可知,现在的 Java 编译器采用复制 finally 代码块的方式,并将其内容插入到 try 和 catch 代码块中所有正常退出和异常退出之前。这样就解释了我们一直以来所熟知的 finally 语句块一定会执行


http://www.ppmy.cn/news/996570.html

相关文章

05-向量的意义_n维欧式空间

线性代数 什么是向量&#xff1f;究竟为什么引入向量&#xff1f; 为什么线性代数这么重要&#xff1f;从研究一个数拓展到研究一组数 一组数的基本表示方法——向量&#xff08;Vector&#xff09; 向量是线性代数研究的基本元素 e.g. 一个数&#xff1a; 666&#xff0c;…

StarRocks Friends 广州站精彩回顾

上周六&#xff0c;StarRocks & Friends 活动在羊城广州成功举行&#xff0c;社区的小伙伴齐聚一堂&#xff0c;共同探讨了 StarRocks 在业界的应用实践和湖仓一体等热门话题。 本文总结了技术交流活动的关键内容和视频资料&#xff0c;感谢社区每一位小伙伴的支持和参与&…

莱佛士学生作品精彩亮相小马宝莉40周年艺术展

由全球领先玩乐公司孩之宝举办的“小马宝莉40周年艺术展”在上海市黄浦区淮海中路862-864号进行展出。 ▲莱佛士学生作品亮相小马宝莉40周年展 本次展览特别邀请多位国内新生代艺术家以小马宝莉为灵感缪斯开展全新创作实践&#xff0c;通过雕塑、绘画、新媒体艺术等作品讲述…

什么是shadow DOM?

Shadow DOM&#xff08;影子DOM&#xff09;是一种用于在Web组件中封装HTML、CSS和JavaScript的技术。它是Web组件的一个重要特性&#xff0c;旨在将组件的结构、样式和行为封装在一个独立的、隔离的DOM树中&#xff0c;从而与主文档的DOM树相互隔离。 传统的Web开发中&#x…

Clamp的介绍

Clamp的介绍 在Unity中&#xff0c;clamp是一种用于限制数值范围的函数。它可以帮助开发者将数值限制在指定的范围内&#xff0c;以避免数值溢出或错误。Unity中提供了多种clamp函数&#xff0c;包括clamp01、clamp、clampMagnitude、clampMin、clampMax和clampValue等。 Cla…

Rust调试【三】

Local Debug: vscode CodeLLDB extension memory leak analysis: Rust and Valgrind FFI Memory wrapping: Foreign Function Interface FFI panic handling: Panic handling

2023-08-01 LeetCode每日一题(英雄的力量)

2023-08-01每日一题 一、题目编号 2681. 英雄的力量二、题目链接 点击跳转到题目位置 三、题目描述 给你一个下标从 0 开始的整数数组 nums &#xff0c;它表示英雄的能力值。如果我们选出一部分英雄&#xff0c;这组英雄的 力量 定义为&#xff1a; i0 &#xff0c;i1 &…

深度学习:使用全连接神经网络FCN实现MNIST手写数字识别

1 引言 本项目构建了一个全连接神经网络(FCN)&#xff0c;实现对MINST数据集手写数字的识别&#xff0c;没有借助任何深度学习算法库&#xff0c;从原理上理解手写数字识别的全过程&#xff0c;包括反向传播&#xff0c;梯度下降等。 2 全连接神经网络介绍 2.1 什么是全连接…