gpt4 book ai didi

Java 自定义异常标准

转载 作者:行者123 更新时间:2023-12-01 12:11:25 24 4
gpt4 key购买 nike

简单的问题,我很难理解异常捕获的工作原理。我知道您可以在 if 语句中嵌套异常,即

int i = 0;
if (i == 0) {
throw new Exception("i cannot be 0");
}

但我不明白在 try/catch block 中的哪个位置满足异常的标准。在我的类(class)中,我们必须创建自己的异常,在本例中,概述的代码如下所示:

public class NegativeValueException extends Exception{

public NegativeValueException() {
super("Numberic values must be nonnegative.");
}

}

据我所知,上面的代码中没有任何标准表明应该抛出异常。

int i = 1;
try {
i = -1;
} catch (NegativeValueException e) { //Thrown exception because the value is negative.
//Where is the criteria that catches this exception?
}

最佳答案

//Thrown exception because the value is negative.

您这样说,但除非您专门编写代码来执行此操作,否则不会抛出NegativeValueException

Java 编译器在底层生成一个异常表。该表存储Exception (Throwable)类型的映射,它们可以出现在哪些行上,以及它们应该转到哪个catch语句。

在您的示例中,修改为引发异常,

int i = 1; // 1
try {
i = -1; // 2
if (i < 0) throw new NegativeValueException(); // 3
} catch (NegativeValueException e) { //Thrown exception because the value is negative. // 4
//Where is the criteria that catches this exception? // 5
}

Java 会映射类似的内容

NegativeValueException - Between 2 and 3 - Goto 4

现在,如果在执行 2 或 3 时,抛出 NegativeValueException,JVM 将转到异常表,找出要跳转到哪个语句,然后执行此操作,将抛出的异常绑定(bind)到catch 参数。

关于Java 自定义异常标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27254389/

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