• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Related to Exceptions

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why this code produces compile time error - exception java.io.FileNotFoundException is never thrown in body of corresponding try statement


while this one doesn't

 
author
Posts: 23956
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

In the first case, you are catching a checked exception -- the compiler can actually check to see if the exception is actually thrown, and hence, complain if it isn't.

In the second case, the Exception class is a super class for many exceptions. Including the RuntimeException class, which is an unchecked exception. These are a class of exceptions which can be thrown at any time, by the JVM.... takes a breath.... Since, the compiler can't confirm that an unchecked exception won't be thrown, and since, the Exception class is a super class of unchecked exceptions, it is allowed.

Henry
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the compiler can see that FileNotFoundException cannot be thrown from the method as its a checked exception. The second snippet catches the parent class Exception, which will catch both checked and unchecked exceptions. So there is a chance (as far as the compile is concerned) that a runtime (unchecked) exception could occur in the try block, even though its empty. Hence the second one is allowed.
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
D'oh just in before me Henry
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic