overridden method does not throw exception

后端 未结 3 2072
清酒与你
清酒与你 2020-12-19 04:09

I have a problem when compiling my code, I\'m trying to make a method of a class throw an personalized exception, given some conditions. But at the time of compiling I get t

3条回答
  •  太阳男子
    2020-12-19 04:43

    You have to declare the throws NoSuchElementException in all superclasses for a checked exception, if you want the subclasses to throw a checked exception in that method.

    You can read more in the Java Language Specification:

    11.2. Compile-Time Checking of Exceptions

    The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.6) or constructor (§8.8.5) must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

    This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled. The checked exception classes (§11.1.1) named in the throws clause are part of the contract between the implementor and user of the method or constructor. The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw (§8.4.8.3).


    While I'm at it, you probably shouldn't use NoSuchElementException, as it's used in the JRE... use a different name.

提交回复
热议问题