Can we use return statement in finally block. Can this cause any problem?
You'll notice that python always returns the last thing to be returned, regardless that the code "reached" return 1 in both functions. A finally block is always run, so the last thing to be returned in the function is whatever is returned in the finally block.
In C#, multiple finally blocks in the same program are not allowed. The finally block does not contain any return, continue, break statements because it does not allow controls to leave the finally block.
When you use finally , any code within that block fires before the method exits. Because you're using a return in the finally block, it calls return false and overrides the previous return true in the try block.
If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).
Returning from inside a finally
block will cause exceptions
to be lost.
A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.
According to the Java Language Specification:
If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and 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).
Note: As per JLS 14.17 - a return statement always completes abruptly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With