Yes it is perfectly legal.
In Java, when a subclass overrides a method from its superclass, it must adhere to certain rules regarding the exceptions it throws. The overriding method in the subclass cannot throw checked exceptions that are broader than the ones thrown by the overridden method in the superclass. However, it is allowed for the overriding method to not throw any exceptions even if the overridden method in the superclass declares that it throws exceptions.
To clarify, if a method in the superclass declares that it throws an exception, the overriding method in the subclass can:
- Throw the same exception type.
- Throw a subtype of the exception declared in the superclass.
- Not throw any exceptions (even if the superclass method declares to throw an exception).
Here’s an example:
class Superclass {
// Method in superclass declares to throw an exception
void someMethod() throws Exception {
// Some code
}
}
class Subclass extends Superclass {// It is legal for the overriding method in the subclass
// to not throw any exceptions, even though the superclass method does.
void someMethod() {
// Some code in the subclass
}
}
In the example above, the Subclass
overrides the someMethod
from the Superclass
and does not declare to throw any exceptions, which is legal.