Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding and Exception

 
gunjan
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone:
"The overriding method can have a different throws clause as long as it doesn't declare any types not declared by the throws clause in the overridden method."
Can some one explain what do they mean by second part that is "not declared by the throws clause in the overridden method".
An example would be very helpful.
Thanks in advance.
Regards
Gunjan
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the class hierarchy
<PRE>java.io
Class FileNotFoundException
java.lang.Object
|
+--java.lang.Throwable
|
+--java.lang.Exception
|
+--java.io.IOException
|
+--java.io.FileNotFoundException
</PRE>
Now, this code compiles OK:
<PRE>
import java.io.*;
class Super {
void method1() throws IOException {
// Code here.
}
}
//--------------------------------------
class Test extends Super {
void method1() throws FileNotFoundException {
// Code here.
}
}
</PRE>
because the overriding method in the subclass Test throws an exception that "IS A" IOException; that is, a subclass of IOException. So it is NOT ADDING any new exceptions because ALL FileNotFoundException ARE IOException.



Finally, if you REVERSE the throws clauses of the methods, THEN you'll get a compile error because the overriding method would be trying to throw MORE GENERAL exceptions than the overridden method in the Base class.



The logic behind it has al lot to do with the OO Commandment that reads something like "Thou shalt be able to substitute a subclass of a base class wherever that base class is expected."
Amen!
 
rajesh subramanian
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this condition is ONLY tue for "Checked execeptions" right??? can some one clarify on this please...
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right. A method can throw an unchecked exception (or more generally, unchecked Throwable) anywhere you want, without declaring it.
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure! Unchecked exceptions don't count for this. The question is very good for a test:
If, for example, a method can throw a NullPointerException, it NEED NOT declare it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic