wood burning stoves 2.0
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

Which Exceptions a method can throw?

Harveen Batra

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?

Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Nope. This is legal:
try {
Reader r = new FileReader("input.txt");
catch (EOFException e) {
System.out.println("File is empty");
catch (IOException e) {
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
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.
I agree. Here's the link: http://aspose.com/file-tools
subject: Which Exceptions a method can throw?
It's not a secret anymore!