Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use "return" in finally block [duplicate]

Can we use return statement in finally block. Can this cause any problem?

like image 669
Rakesh KR Avatar asked Aug 13 '13 09:08

Rakesh KR


People also ask

Can we return in finally block Python?

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.

Can we write return in finally block C#?

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.

Does return override finally?

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.

What happens if there is a return statements in both the try block and finally block in a function?

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).


1 Answers

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.

like image 132
Ankur Lathi Avatar answered Oct 12 '22 12:10

Ankur Lathi