如何在Java 7中实现多捕获? [英] How is multi-catch implemented in Java 7?

查看:117
本文介绍了如何在Java 7中实现多捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7编译器如何处理多捕获块?一个简单的实现是生成字节码,就好像存在多个catch块一样。但是,我从多个来源收集到的情况并非如此 - 处理多个异常类型的catch块在编译期间不会产生重复的字节码。



<那么,它是如何工作的?是否有新的字节码指令告诉JVM多捕获块?

解决方案

基于 Java虚拟机规范,异常编译如下(总结):




  • 尝试代码正常运行

  • 每个catch块都被编译为好像它是一个单独的方法

  • 有一个异常表将执行流程重定向到右边的catch块



使用时一个多catch子句,catch块是相同的(只出现一次),但异常表将包含一个具有相同的from,to和target值的条目。



例如,此代码:

  public static void main(String args [])throws InterruptedException {
try {
System.out.println(为什么不呢?);
} catch(IllegalArgumentException e){
System.out.println(here);
} catch(IllegalStateException | ArithmeticException e){
System.out.println(there);
}
}

生成以下异常表(在我的机器上):

 从目标类型
0 8 11类java / lang / IllegalArgumentException
0 8 23类java / lang / IllegalStateException
0 8 23类java / lang / ArithmeticException


How is the Java 7 compiler handling multi-catch blocks ? A naive implementation would be to generate bytecode as if multiple catch blocks are present. However, I have gathered from multiple source that this is not the case - A catch block that handles multiple exception types contributes no duplicate bytecode during compilation.

So, how does it work ? Is there a new bytecode instruction that tells the JVM about multi-catch blocks ?

解决方案

Based on the Java Virtual Machine Specification, exceptions are compiled as follows (in summary):

  • try code is run normally
  • each catch block is compiled as if it were a separate method
  • there is an exception table to redirect the execution flow to the right catch block

When using a multi catch clause, the catch block is the same (appears only once), but the exception table will contain one more entry with the same from, to and target values.

For example, this code:

public static void main(String args[]) throws InterruptedException {
    try {
        System.out.println("why not?");
    } catch (IllegalArgumentException e) {
        System.out.println("here");
    } catch (IllegalStateException | ArithmeticException e) {
        System.out.println("there");
    }
}

generates the following exception table (on my machine):

   from    to  target type
       0     8    11   Class java/lang/IllegalArgumentException
       0     8    23   Class java/lang/IllegalStateException
       0     8    23   Class java/lang/ArithmeticException

这篇关于如何在Java 7中实现多捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆