简体   繁体   English

向“ throws”添加未使用的异常

[英]Adding Unused Exceptions to 'throws'

Why does the Java compiler allow exceptions to be added via throws even when they're not possibly able to be thrown? 为什么Java编译器即使在不可能throws异常的情况下也允许通过throws添加异常?

example: 例:

private static void foo() throws java.io.FileNotFoundException {
    System.out.println("no possible FileNotFoundException here");
}

The above code compiles just fine, but it's not possible for a FileNotFoundException to be thrown. 上面的代码可以很好地编译,但是不可能抛出FileNotFoundException

I would suggest maintenance: because you might want to change that method later to add an operation that could throw a FileNotFoundException , and you want to force all callers of this method to know what to do if that method should be changed to throw FileNotFoundException in the future. 我建议维护:因为您以后可能想更改该方法以添加一个可能抛出FileNotFoundException的操作,并且您想强制此方法的所有调用方知道如果应将该方法更改为在该方法中抛出FileNotFoundException怎么办。未来。

Another manifestation of the issue is that a subclass may override this method and throw the exception, and this cannot be determined by compiling the superclass alone. 该问题的另一个体现是子类可以重写此方法并引发异常,而这不能仅通过编译超类来确定。

Because the compiler isn't smart enough to find out every exception? 因为编译器不够聪明,无法找出每个异常? It sounds quite logical that Java can't know the possible outcomes for all algorithms. Java无法知道所有算法的可能结果,这听起来很合逻辑。 Just like a programming language can never prove a mathematical exception, it can only execute mathematics. 就像编程语言永远不能证明数学上的例外一样,它只能执行数学。

This means that an obvious mathematical "infinite loop", isn't always obvious to the programming language. 这意味着明显的数学“无限循环”对于编程语言而言并不总是显而易见的。 I think that for such reasoning, the compiler doesn't bother looking at what will be executed. 我认为,出于这种推理,编译器不必理会要执行的内容。

If the compiler would have to pre-check for all exceptions the coder writes, it might spend "days" checking the code. 如果编译器必须预先检查编码器编写的所有异常,则可能需要“几天”来检查代码。 All in all it just seems better to have the programmer responsible for the exceptions. 总而言之,让程序员负责异常似乎更好。 Either way, it doesn't hurt. 无论哪种方式,它都不会造成伤害。

Checked exceptions are validated by the compiler only in the try { } block, method bodies are not validated. 编译器仅在try { }块中对检查的异常进行验证,而方法主体不进行验证。 There are multiple reasons, the complexity of such check being one, the fact that a child class can override the method and decide to throw the exception is a second. 原因有多种,第二种是这种检查的复杂性,子类可以覆盖该方法并决定抛出异常。

In Netbeans 7.3.1, this would show up as an "unreported exception" and it will warn you that it must be caught or declared. 在Netbeans 7.3.1中,这将显示为“未报告的异常”,并警告您必须捕获或声明它。 So it would be an error. 因此,这将是一个错误。 It depends on your tool. 这取决于您的工具。

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

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