• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Throwable, Exception and IOException

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?!? "
 
I knew that guy would be trouble! Thanks tiny ad!
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic