| Author |
Related to Exceptions
|
Prince Chauda
Greenhorn
Joined: Feb 13, 2008
Posts: 8
|
|
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
Sheriff
Joined: Sep 28, 2004
Posts: 16686
|
|
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
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Tom Johnson
Ranch Hand
Joined: May 11, 2005
Posts: 142
|
|
|
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.
|
<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>
|
 |
Tom Johnson
Ranch Hand
Joined: May 11, 2005
Posts: 142
|
|
D'oh just in before me Henry
|
 |
 |
|
|
subject: Related to Exceptions
|
|
|