Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
d jones
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am a little confused with the following code:



In the above method even though we are throwing an exception it does not have to be declared in the method signature
because the return statement is in the finally block.

However if we put the return statement outside the finally block:




this code will not compile because the InterruptedException needs to be declared in the method signature.

Could anyone please let me know why the first method compiles?
From what I understand about exception handling - if a method throws an exception then it must be declared.
I'm guessing that if the return statement is in the finally block that the int returned is taking precedence over the exception being thrown since finally block is always executed???

Many Thanks
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from the Java Language Specification 14.20.2

If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:

* If the finally block completes normally, then the try statement completes abruptly for reason R.
* If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic