overridden method does not throw exception

后端 未结 3 2071
清酒与你
清酒与你 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:47

    The problem becomes clear when you have such code as this using your class and interface:

    Graph g = new UNGraph();
    int id = g.getId(...);
    

    The interface Graph doesn't declare that it throws the checked exception NoSuchElementException, so the compiler would allow this code without a try block or a throws clause on whatever method this code is in. But the overriding method clearly can throw the checked exception; it has declared as much. This is the reason that an overriding method cannot throw more checked exceptions than an overridden or abstract method. There would be a difference in how the calling code needs to handle checked exceptions, depending on the actual type of the object.

    Have the interface's method declaration declare that it throws NoSuchElementException or have the implementing class's method handle the NoSuchElementException itself.

提交回复
热议问题