Can we use "return" in finally block

Rakesh KR picture Rakesh KR · Aug 13, 2013 · Viewed 54.4k times · Source

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

Answer

Ankur Lathi picture Ankur Lathi · Aug 13, 2013

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.