• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Which Exceptions a method can throw?

 
Harveen Batra
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question pertains to the following line:-
"The catch clause must match the exceptions listed in the throws clause but the method can throw any subclass of an exception listed in the throws clause"
Does that mean that no catch clause can be defined for exceptions which are subclasses and not formally defined with the trows clause???
relieve me of this anamoly?

Harveen
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope. This is legal:
<code><pre>
try {
Reader r = new FileReader("input.txt");
r.read();
}
catch (EOFException e) {
System.out.println("File is empty");
}
catch (IOException e) {
e.printStackTrace();
}
</pre></code>
The read() method is only declared to throw IOException, but you can catch EOFException because it's a subclass of IOException.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, if you have ClassA and it's subclass, ClassB, you can use an instance of ClassB anywhere that you would use an instance of ClassA. That includes throwing exceptions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic