File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding and Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding and Exception" Watch "Overriding and Exception" New topic
Author

Overriding and Exception

gunjan
Ranch Hand

Joined: Jan 28, 2000
Posts: 33
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


Regards<BR>Gunjan
Tony Alicea
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
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!


Tony Alicea
Senior Java Web Application Developer, SCPJ2, SCWCD
rajesh subramanian
Greenhorn

Joined: Jan 03, 2007
Posts: 1
this condition is ONLY tue for "Checked execeptions" right??? can some one clarify on this please...
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Right. A method can throw an unchecked exception (or more generally, unchecked Throwable) anywhere you want, without declaring it.


"I'm not back." - Bill Harding, Twister
Tony Alicea
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overriding and Exception