In Java exceptions, the block of code in finally is used by the JVM to ensure that the statement in the try is executed whether or not it is an exception. What would the execution logic look like if the finally block contained a return statement?
Returns in try and finally
public class ExceptionExample {
private static String test(a) {
String step = "";
try {
int result = 1/1;
return step += ",try";
} catch (Exception e) {
return step += ",catch";
} finally {
return step += ",finally"; }}public static void main(String[] args) {
System.out.printf("return order: %s", test()); }}Copy the code
The execution result
return order: ,try,finally
Copy the code
Return in catch and finally
public class ExceptionExample {
private static String test(a) {
String step = "";
try {
int result = 1/0;
return step += ",try";
} catch (Exception e) {
return step += ",catch";
} finally {
return step += ",finally"; }}public static void main(String[] args) { System.out.println(test()); }}Copy the code
The execution result
return order: ,catch,finally
Copy the code
As you can see from the two examples above, if a return statement exists in finally, the return execution logic is as follows:
- An expression after a return statement in a try or catch;
- Execute an expression after a return statement in finally;
- Execute the return statement in finally;