Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Doubt..

 
Krishnakumar
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question 1
----------

If I write a code like the one below why does it not give a compilation error. If I change Exception to IOException it does throw a compilation error.





Question 2
----------

If an IOException is thrown, then even an Exception can catch it because it is its super class. Then why not an Object.

 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The exceptions that are subclasses of RuntimeException are unchecked. So by catching an Exception you are looking for a wide range of exceptions. But if you choose a specific checked exception, then you need to make sure there is some code in the try block that has the potential for throwing that exception.

The parameter in the catch block must be a subclass of Throwable.
 
Jeff Tian
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi KrishnaKumar.

Further to what Keith said,
I think question one also involves "implicit import" of java.lang.* library. I read somewhere that this happens, but I dunno much about it.

Note that Exception and other exceptions such as SecurityException, ArithmeticException are in the library and do not need any additional import declaration. See API.

If you want to use IOException, you have to import java.io and you also have to put some code in try block that will possibly throw IOException eg

FileReader fr = new FileReader("someFileName.txt");

As for Question 2, only Throwable and subclass can be caught (Keith) and while an exception is an object an object is not an exception.
[ March 29, 2005: Message edited by: Jeff Tian ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic