File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Throwable, Exception and IOException

 
Anselme Bender
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following class I can't understand why the compiler complains when using
catch(java.io.IOException t)
where it doesn't with either :
catch(Throwable t) // OK
OR
catch(Exception t) // OK
Is it the compiler responsability to do it that way ?
Thanks
public class AQuestion
{
public static void main(String args[])
{
System.out.println("Before Try");
try
{
// Nothing here
}
// catch(Throwable t) // OK
// catch(Exception t) // OK
catch(java.io.IOException t) // doesn't compile
{
System.out.println("Inside Catch");
}
System.out.println("At the End");
}
}
 
Anselme Bender
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One addition.
I should have written my question :
Why the compiler doesn't complain if the catch statement uses Throwable or Exception
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the code inside the main method can throw a number of RuntimeExceptions (like NullPointerException etc..)
so you can attempt to catch Throwable and Exception (which are the super classes of Runtime exceptions).
However, IOException is a checked exception. Since your method isnt able and wont throw anyway in your code an IOException (cause println or anything else there doesnt throw that kind of exception), the compiler complains and tells you: " hey you cant possibly get that IOExcpetion! so why are you trying to catch it?!? "
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic