Tuesday, May 23, 2006

Overriding and throws clause

Overriding and throws clause

The finalize() method in Object can throw any Throwable Object. Overriding methods can limit the range of throwables to unchecked exceptions. Further Overridden definitions of this method in subclasses will not be able to throw checked exceptions.

Ans: Yes

public class Runner {

public static void main(String[] args) {

MyType myType = new MyType();

myType=null; // Line 1
java.util.ArrayList arrayList = new java.util.ArrayList(); //line 5

while(true) {
arrayList.add(new String("waste"));

}
}
}

class MyType{
protected void finalize() throws Exception{
System.out.println("bye");
}
}

How do u say "yes". In the above example I used an "Exception" in the throws clause which is a "checked Exception". The compiler didn't complain about any thing.

Let's look again at the second and third sentences you quoted: "Overriding methods can limit the range of throwables to unchecked exceptions. Further Overridden definitions of this method in subclasses will not be able to throw checked exceptions." Now I assumed that these two sentences went together. That is when they talk about "further overridden definitions", they mean further after you've already overridden with a method that limits the range of throwables to unchecked exceptions. You haven't done that, so you're getting different results than they describe.

Try this:

code:

class Foo {
protected void finalize() {
System.out.println("finalize in Foo");
}
}


class Bar extends Foo {
protected void finalize() throws Exception {
System.out.println("finalize in Bar");

}
}

This won't compile, because Foo overrides finalize() in a way that limits the range to only unchecked exceptions. And Bar extends Foo. So finalize() in Bar can't throw any new checked exceptions. That's what the quoted text is talking about.

0 Comments:

Post a Comment

<< Home