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

Reg. Exception hierarchy

 
Angela Narain
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic