my dog learned polymorphism
The moose likes Beginning Java and the fly likes Related to Exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Related to Exceptions" Watch "Related to Exceptions" New topic

Related to Exceptions

Prince Chauda

Joined: Feb 13, 2008
Posts: 8
Why this code produces compile time error - exception is never thrown in body of corresponding try statement

while this one doesn't

Henry Wong

Joined: Sep 28, 2004
Posts: 20154

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.


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="" 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
I agree. Here's the link:
subject: Related to Exceptions
jQuery in Action, 3rd edition