简体   繁体   English

为什么算术异常是未经检查的异常?

[英]Why Arithmetic Exception is an unchecked exception?

有人可以解释为什么算术异常属于未检查的异常类别吗?我已经搜索了它,但没有正确的答案。如果有人回答,将不胜感激。

ArithmeticException extends RunttimeException , therefore it's unchecked. ArithmeticException扩展了RunttimeException ,因此未经检查。

Why this design decision? 为什么要设计决定? If ArithmeticException was checked, then you would have to encapsulate every (!) integer division in try catch or add a throws to the surrounding method. 如果选中了ArithmeticException ,则必须在try catch封装每个(!)整数除法,或者向周围的方法中添加throws

The following program wouldn't compile: 以下程序无法编译:

class MyClass {
    int i = 10;
    void myMethod() {
        int j = 1 / i;
        // do something with j
    }
}

You would have to write either 您将不得不写

void myMethod() throws ArithmeticException {
    int j = 1 / i;
    // do something with j
}

or 要么

void myMethod() {
    int j;
    try {
        j = 1 / i;
    } catch (ArithmeticException e) {
        j = ...; // what value should be used?
    }
    // do something with j
}

At least to me, that would be very annoying. 至少对我来说,这很烦人。

为了使开发人员免于处理由于编程错误而导致的各种异常,例如从数组末尾掉落,除以零等等,因此将某些异常指定为未经检查的异常(这些异常源自RuntimeException ),并且不需要声明。

Because it's akin to an illegal argument exception. 因为它类似于非法的参数异常。

All of IllegalArgumentException , IllegalStateException and NullPointerException are seen as programming errors and unchecked to avoid the excessive proliferation of throws clauses throughout code that in principle might throw any and all of those exceptions they're unchecked. 所有IllegalArgumentExceptionIllegalStateExceptionNullPointerException都被视为编程错误,并且未经检查,以防止throws子句在整个代码中过度扩散,因此原则上可能抛出未经检查的所有异常。

There's only a syntatic difference between: 之间只有一个语法上的差异:

y=a/b;

And

y=div(a,b);

Sounds like a old thread, but in case it helps, here are some detailed thoughts on the topic with more insights, reasoning & API references. 听起来像一个旧线程,但如果有帮助,这里有一些关于此主题的详细想法,其中包含更多的见解,推理和API参考。 FAQ about checked exception and unchecked exception? 关于检查异常和非检查异常的常见问题?

Hopefully this will answer in more depth. 希望这会更深入地回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM