Return Statement in Try-Catch
In this lesson, we'll walk through the case of return statements in the try-catch block.
We'll cover the following
Return statements
When both
catch
andfinally
return values, what will be the final result?
In this case, we have to separate the solution into referential and primitive returning values.
Returning primitive values
class Exceptions {public static void main( String args[] ) {System.out.print("Returned Value is: "+method1());}public static int method1() {int value = 1;try{throw new ArrayIndexOutOfBoundsException();}catch(ArrayIndexOutOfBoundsException e){value = 2;System.out.println("Exception caught value is "+ value);return value; // value is being returned inside catch}finally{value = 3;System.out.println("Finally value is now "+ value);return value; // value is being returned inside finally}}}
The
finally
block will still execute, even if thecatch
block has a return statement.
If both catch
and finally
return, the receiving method will get the returned value from the finally
block.
Returning referential values
class Parent {public static void main(String[] args) {Child c = new Child();System.out.print("Returned Value is "+c.method1()[0]);}}class Child{public int[] method1() {int value = 10;int[] arr = {1};try{System.out.println(arr[4]);}catch(ArrayIndexOutOfBoundsException e){System.out.println("Exception caught value is "+ arr[0]);return arr; // value is being returned from inside catch}finally{arr[0] = 2;System.out.println("Finally value is "+ arr[0]);}return arr; //returning a referential type variable}}
Here, the returned value is 2, which was updated in the finally
block.
With the primitive types (passed by value), the returned value comes from finally
. Here, we don’t have a return statement inside the finally
block. So, if the exception is caught, the result is returned through the return
statement inside the catch
clause. Here, finally
has a referential type variable through which the value can be accessed and updated, as seen above.
This results in the reference having an updated value. However, if finally
was simply returned without updating, the value would also be returned.
Highlights
- In a try-catch-finally block that has
return
statements, only the value from thefinally
block will be returned. - When returning reference types, be aware of any updates being done on them in the
finally
block that could end up in unwanted results.