Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Related to Exceptions

 
Prince Chauda
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • 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

 
Henry Wong
author
Marshal
Pie
Posts: 21122
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
D'oh just in before me Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic