Forums Register Login

Exception Handling

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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).
this is supposed to be a surprise, but it smells like a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 562 times.
Similar Threads
Unreachable, return in finally or catch
checked exceptions!
where to use return statement
Exception and finally
Finally abrupt return
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 06:56:16.