aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reg. Exception hierarchy 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 "Reg. Exception hierarchy" Watch "Reg. Exception hierarchy" New topic
Author

Reg. Exception hierarchy

Angela Narain
Ranch Hand

Joined: Apr 14, 2001
Posts: 327
Why does the below give an compile-time error ?
class MyException extends Exception {}
class SubException extends MyException {}
public class Derived {
public static void main(String args[] ) {
try
{
show();
}
catch( SubException e ) { }
}
public static void show() throws MyException {
throw new MyException();
}
}
And why does it get compile , once i add the line :
public class Derived {
public static void main(String args[] ) throws MyException {
try
{
show();
}
catch( SubException e ) { }
}
public static void show() throws MyException {
throw new MyException();
}
}
What is the exception hierarchy to be following when calling
methods throwing such checked exceptions ?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12803
    
    5
The rule is the same as for casting other references. Your catch statement must match the thrown exception OR a parent exception.
In your case the compiler sees that your catch won't handle a MyException, and since this is a "checked" exception, this causes an error.
Bill
------------------
author of:
Muhammad Farooq
Ranch Hand

Joined: May 08, 2001
Posts: 356
Angela, here you are throwing a parent Exception (MyException)in the method show() and catching a child Exception (SubException) thats why u r getting a compile time error. If you are throwing a checked exception in a method(MyException in show() ), then the calling method( main() ) should catch that exception or the parent class of that Exception. Try to change SubException with either MyException or Exception , it will compile.
For your second querry, when you declare the throws clause in the method (main() )declaration, you are actually defering that Exception (MyException ) to the calling method of this method (main() in this example)
HTH.
--Farooq


Muhammad Farooq<br />Sun Certified Programmer for Java 2 Platform<br />Oracle8i Certified Professional Database Administrator
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reg. Exception hierarchy