为什么Java编译器允许在throws部分中列出异常

为什么Java编译器允许在throws部分中列出异常

本文介绍了为什么Java编译器允许在throws部分中列出异常,该方法无法抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一些代码显然无法抛出异常,那么Java编译器似乎不一致,并且您编写了声明代码可以抛出该异常的周围代码。

The Java compiler seems inconsistent if there is some code that clearly can not throw an exception, and you write surrounding code that declares that the code can throw that exception.

请考虑以下代码段。

A catch 永远不会抛出的异常。

A catch of an exception that is never thrown.

public void g(){
        try {

        } catch (FileNotFoundException e) {//any checked exception

        }

}

带有消息的编译错误

Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body



Snippet2



A 抛出声明,表示永远不会抛出异常。

Snippet2

A throws declaration indicating an exception that is never thrown.

public void g() throws FileNotFoundException{
}

它编译得很好。

因此,第一个代码片段的结果显示编译器可以计算方法是否可以抛出中抛出的异常列表。因此,似乎编译器故意没有报告第二个片段的错误。但为什么?为什么编译器允许您在 throws 部分中编写异常,即使编译器知道这些异常不能被抛出?

Therefore, the results of the first code snippet shows that the compiler can calculate if a method can throw an exception listed in the throws list. So it seems the compiler is deliberately not reporting an error for the second snippet. But Why? Why does the compiler allow you to write exceptions in throws section even if it the compiler knows thst those exceptions can not be thrown?

推荐答案

编译器允许这样做,因为该方法的 throws 子句是该方法的签名的一部分,而不是其实现的一部分。 。旧的实现可能抛出了已检查的异常,但新的异常可能没有。或者签名的设计者可能希望为实现者提供在不总是必要时抛出已检查异常的灵活性。

The compiler allows this because the throws clause of the method is part of the signature of the method, rather than part of its implementation. It is possible that the implementation might change at some point, while keeping the signature the same. An old implementation might have thrown a checked exception, but the new one might not. Or the designer of the signature might have wanted to give the implementer the flexibility to throw a checked exception when that is not always necessary.

这篇关于为什么Java编译器允许在throws部分中列出异常,该方法无法抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:00