Java Reference
In-Depth Information
A finally block is like any block of code, and can perform any operations.
Notice that the finally block in MyFileUtilities3 contains another try/catch
block because closing a file possibly throws an IOException.
Overridden Methods and Exceptions
In Chapter 6, “Understanding Inheritance,” we discussed method overriding,
in which a method in a child class can override a method in the parent class.
One of the rules I mentioned about method overriding is that a child method
cannot throw “more” exceptions than the overridden parent method. We are
now ready to discuss the details of this rule.
When I say “more” exceptions, I am not referring to the number of exceptions
thrown by the child method, even though that is part of it. What I mean by
“more” is that a child class cannot throw an exception that, by polymorphism, is
not at least declared by the overridden method in the parent.
This is best seen by an example. Suppose that we have a class named Parent
that contains a method named connect(). The connect() method declares that it
throws a java.io.IOException.
import java.io.IOException;
public class Parent
{
public void connect() throws IOException
{
System.out.println(“Inside connect() in Parent”);
throw new IOException();
}
}
The following Child1 class extends the Parent class and overrides the con-
nect() method. The connect() method in Child1 declares that it throws a java
.net.SocketException. Is this valid method overriding? Yes, because Socket-
Exception is a child class of IOException, so SocketException is a “lesser”
exception than IOException.
import java.net.SocketException;
public class Child1 extends Parent
{
public void connect() throws SocketException
{
System.out.println(“Inside connect() in Child1”);
throw new SocketException();
}
}
Search WWH ::




Custom Search