I have the following piece of code.
public static void main(String[] args) {
System.out.println(returnString());
}
private static String returnString(){
try {
System.out.println("Executing try");
return "Return try value";
} catch (Exception e){
System.out.println("Executing Catch");
return "Return catch value";
} finally {
System.out.println("Executing finally");
return "Return finally value";
}
}
The output for this is
Executing try
Executing finally
Return finally value
If I change my finally block to not return anything like
public static void main(String[] args) {
System.out.println(returnString());
}
private static String returnString(){
try {
System.out.println("Executing try");
return "Return try value";
} catch (Exception e){
System.out.println("Executing Catch");
return "Return catch value";
} finally {
System.out.println("Executing finally");
}
}
Then the output is
Executing try
Executing finally
Return try value
Now I understand that finally is always executed except if we call system.exit(0); called or the JVM crashes.
What I'm not able to understand is why the return value has changed ? I would still expect it to return the value of the try block.
Can anyone explain why the finally value is take into consideration and not the return value from the try block ?
Please refrain from answering because finally is executed even if there is an return in try block ... or finally doesn't execute only if there is a system.exit(0); called or the JVM crashes. as I know that.
EDIT :
(As per Dirk comment on this)
public static void main(String[] args) {
System.out.println(returnString());
}
private static String returnString(){
try {
System.out.println("Executing try");
return printString("Return try value");
} catch (Exception e){
System.out.println("Executing Catch");
return printString("Return catch value");
} finally {
System.out.println("Executing finally");
return printString("Return finally value");
}
}
private static String printString(String str){
System.out.println(str);
return str;
}
Output:
Executing try
Return try value
Executing finally
Return finally value
Return finally value