• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • 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: 23923
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
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic