For try-finally
or try-catch-finally
: A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
However, In terms of returning a value with a return
statement:
- The
try
and catch
block's returning value with return
statement is remembered.
- If the
finally
block doesn't have a return statement, After executing the finally
block:
- If no exception happened and(or) wasn't caught by the
catch
block: remembered returning value of the try
block is returned.
- else, remembered returning value of the
catch
block is returned.
else, it will return value with the finally block's return statement forgetting about the try
and(or) catch
block's return.
public static Integer returnData()
{
Integer x = null;
try{
System.out.println("try the x: "+x);
return x;
}
finally
{
x = 5; // here i am assigning 5
System.out.println("finally is printed with: "+x); // printing 5
return x;
}
}
public static void main(String[] args) {
System.out.println("Printing the return value in main: "+returnData());
// printed 5 according to the assignment in finally block
}
Even if the above function should return null
in the try
block, you will see that running the above example will print:
try the x: null
Hi finally is printed with: 5
Printing the return value in main: 5
Now, if you remove the return statement from finally
block, you will see the following output:
try the x: null
finally is printed with: 5
Printing the return value in main: null
As null
was remembered as the returning value from the try
block.
check out the jls: 14.20.2. Execution of try-finally and try-catch-finally For more details.