gpt4 book ai didi

java - 自定义异常处理

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

当使用 throws 关键字抛出自定义异常时,我需要显式处理它,即。 e.我需要调用 try-catch block 内的方法,但同时使用 throws 抛出内置异常关键字如果我不使用 try-catch block 在主方法内处理它,那么我不会收到任何编译时错误,发生运行时异常是可以接受的。我的问题是,当我不处理自定义异常时,我会收到编译时错误,指出:未处理的异常。虽然内置异常并非如此

class B
{
public void show() throws ArithmeticException
{
throw new ArithmeticException();
}
}

public class Myclass {

public static void main(String[] args) {
B b = new B();
b.show();
}
}

当我编译上述代码而不处理算术异常时,我不会收到任何编译时错误

class A extends Exception
{
public A()
{
System.out.println("Exception thrown");
}
}

class B extends A
{
public void show() throws A
{
throw new A();
}
}

public class Myclass {

public static void main(String[] args) {
B b = new B();
b.show();
}
}

但是当我编译上面的代码时,它给了我一个编译时错误,说我没有处理类型 A 的异常。所以,我的问题是为什么允许不处理内置异常,而必须处理自定义异常。

最佳答案

So my question is why it is allowable not to handle built-in exception, while it is compulsory to handle custom exceptions?

事实并非如此。这实际上取决于您的“自定义异常”。如果未选中此选项,则无法在编译时对其进行检查 - 例如算术异常。为什么?因为,它必须实际执行操作来查明除数是否为零并抛出异常,而这仅在运行时发生。因此,未经检查的异常总是扩展RuntimeException

因此,受检查的异常是可以在编译时检查的异常。因此,它也在编译时被(显式)处理。

关于java - 自定义异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46350389/

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