• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Catching an unchecked exception which is never thrown

 
Tonguc Koc
Greenhorn
Posts: 13
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I'm having difficulty in understanding the example below where the former one doesn't compile whereas the latter does.
What is the reason behind it?



 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FileNotFoundException (and all its subclasses) is (are) a checked exception, so the compiler checks if the given exception is handled or declared (the handle-or-declare rule), but also verifies if the code inside the try-block does throw the given exception. That's why the 1st snippet fails to compile (it's empty, so no code that could throw a FileNotFoundException).

In the 2nd snippet you catch Exception and all its subclasses (so also possible runtime exceptions). Because a runtime exception happens at runtime (hence its name) the compiler does not complain, because the code block (although empty) could throw a runtime exception when you run the program.
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is interesting.

I actually looked into the JLS' section 14.21 ( 'unreachable code' ) to see if there was a clue or something. I couldn't find anything that can give a hint.

The JLS states that

JLS wrote:A catch block C is reachable iff both of the following are true:

Either the type of C's parameter is an unchecked exception type or Throwable; or some expression or throw statement in the try block is reachable and can throw a checked exception whose type is assignable to the parameter of the catch clause C.

An expression is reachable iff the innermost statement containing it is reachable.

See ยง15.6 for normal and abrupt completion of expressions.

There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.

The Block of a catch block is reachable iff the catch block is reachable.


And that doesn't explain this case. I think Roel's explanation that Exception covers RuntimeException ( Unchecked exception probably is a better word here ) could be the only reason and interestingly the JLS does say that, "A catch block C is reachable iff both of the following are true:

Either the type of C's parameter is an unchecked exception type or Throwable";
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic