Consider following classes:
class X
{
public void met()
{
}
}
and
class Y extends X
{
public void met() throws NullPointerException
{
throw new NullPointerException();
}
}
I understand that the overriding method in the subclass, has to throw either the same or a subclass of the exception thrown in the overridden method.
Do Java methods always throw at least an exception of the type Exception?
...In other words the compiler adds throws Exception
So the class X would look like this
class X {
public void met() throws Exception {
}
}
I want to clarify that I am not mistaken about the fact that the default exception handler Exception is always added.
Related questions:
解决方案
There are two types of Exceptions: checked Exceptions (like ParseExceptionwhen parsing text) and unchecked Exceptions (like NullPointerException).
Checked Exceptions must be declared in the method signature. Unchecked Exceptions may be declared in the method signature.
When overriding methods (from an interface or a super class) you only have to specify the exceptions, that you are throwing in your implementation. You cannot declare to throw checked exceptions in an implementation that are not allowed in the overridden method.
This is allowed:
class X { void someMethod() }
class Y extends X { @Override void someMethod() throws UncheckedException }
This is not allowed:
class X { void someMethod() }
class Y extends X { @Override void someMethod() throws CheckedException }
This is also allowed:
class X { void someMethod() throws CheckException }
class Y extends X { @Override void someMethod() }