wood burning stoves*
The moose likes Beginning Java and the fly likes Which Exceptions a method can throw? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Which Exceptions a method can throw?" Watch "Which Exceptions a method can throw?" New topic
Author

Which Exceptions a method can throw?

Harveen Batra
Greenhorn

Joined: Nov 14, 2000
Posts: 5
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

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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.
 
GeeCON Prague 2014
 
subject: Which Exceptions a method can throw?