gpt4 book ai didi

java - 我如何知道在字节码级别引发的异常的类型?

转载 作者:行者123 更新时间:2023-11-30 04:14:21 24 4
gpt4 key购买 nike

throw 语句的显式调用在字节码级别上用 athrow 指令表示。

例如下面的代码片段:

private static SQLException thrower() throws SQLException
{
throw new SQLException();
}

被翻译成如下字节码:

   private static java.sql.SQLException thrower()   throws java.sql.SQLException;
Signature: ()Ljava/sql/SQLException;
Code:
0: new #29; //class java/sql/SQLException
3: dup
4: invokespecial #31; //Method java/sql/SQLException."<init>":()V
7: athrow

我的问题是:仅通过分析字节码,我如何知道抛出的异常的类型?

观察:值得一提的是,当我们在源代码中调用throw语句时,并不总是实例化一个新的异常类型。因此,查看 new 指令的参数类型并不是解决方案。

最佳答案

这是不可能的,因为给定的指令可能会抛出不止一种类型的异常。

考虑代码

throw foo ? new ClassCastException() : new IOException();

在更复杂的情况下,您可能会抛出一些在运行时确定类型的东西,甚至是从运行时构造的类创建的东西。

关于java - 我如何知道在字节码级别引发的异常的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18770316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com