Java Reference
In-Depth Information
You can override a parent method that throws an exception and not declare
any exceptions in the child class method. For example, the following Child2
class extends Parent and overrides the connect() method. The child method does
not declare any exceptions, which is certainly not “more” than an IOException.
public class Child2 extends Parent
{
public void connect()
{
System.out.println(“Inside connect() in Child2”);
}
}
Let's see an example that does not work. The following Child3 class extends
Parent and attempts to override connect(). A compiler error is generated
because connect() in Child3 declares that it throws Exception, which is “more”
of an exception than IOException.
public class Child3 extends Parent
{
public void connect() throws Exception //Does not compile!
{
System.out.println(“Inside connect() in Child3”);
throw new Exception();
}
}
♦
Why Does This Rule Exist When
Overriding a Method?
A method in a child class, overriding a method in its parent class, cannot throw more excep-
tions or greater exceptions than what the parent class has declared. This might seem like
an odd rule in Java, but there is a specific reason for it. If you were allowed to have a child
method throw a greater exception, you could create a situation in which a checked excep-
tion avoided the Handle or Declare Rule.
Let me show you with a simple example. Suppose that we have the following class
named Parent:
public class Parent
{
public void connect()
{
System.out.println(“Inside connect() in Parent”);
}
}
continued