Why does the Java compiler allow exceptions to be listed in the throws section that it is impossible for the method to throw

前端 未结 5 621
闹比i
闹比i 2020-12-04 01:52

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

5条回答
  •  囚心锁ツ
    2020-12-04 02:31

    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.

提交回复
热议问题