Java written interview interview summary-there are various types of return in try, catch, finally statements

Posted Jun 27, 20206 min read

Foreword

In the past, I often encountered or was asked the execution order of the try-catch-finally grammar block during the brush test questions and interviews. Today I took the time to sort out this knowledge point and then recorded it.

Text

This article mainly elaborates various situations by way of examples. I will divide it into two large cases according to the try-catch-finally syntax block:try-catch syntax block and try-catch-finally statement block, and then In each case, go into specific discussions.

One, try-catch statement block

We can look at the following program:

public static void main(String[]args) {

    System.out.println(handleException0());
  }

  /**
   * Try and catch have return
   * @return
   */
  private static String handleException0() {
    try{
      System.out.println("try start");
      String s = null;
      int length = s.charAt(0);
      System.out.println("try end");
      return "The return value of the try block";
    }catch(Exception e){
      System.out.println("Exception caught");
      return "Catch's return value";
    }
  }

Results of the:

try to start
Exception caught
The return value of catch

Analysis:The program first executes the code in the try block. An exception is found in the try block. The code behind the try block will not be executed(naturally, it will not return), then enter the catch block that matches the exception, and then enter the catch The code is completed in the block. When the return statement in the catch is executed, the program is aborted, and then the final result of the return is returned.

Second, try-catch-finally statement block

I divided this grammatical block into 4 situations, and I will list them one by one below.

1. In the first case, there is a return in the try block, and an exception is caught

example 1:

public static void main(String[]args) {
  String result = handleException1();
  System.out.println(result);
}
private static String handleException1() {
  try{
    System.out.println("try start");
    String str = null;
    int length = str.length();
    System.out.println("try end");
  }catch(Exception e){
    System.out.println("Exception caught");
  }finally {
    System.out.println("finally block execution completed");
  }
  return "Final result";
}

The results of Example 1 are as follows:

try to start
Exception caught
Finally the block is executed
Final result

Example 2:

public static void main(String[]args) {
  String result = handleException2();
  System.out.println(result);
}
private static String handleException2() {
  try{
    System.out.println("try start");
    String str = null;
    int length = str.length();
    System.out.println("try end");
    return "The return value of the try block";
  }catch(Exception e){
    System.out.println("Exception caught");
  }finally {
    System.out.println("finally block execution completed");
  }
  return "Final result";
}

The execution result of Example 2 is as follows:

try to start
Exception caught
Finally the block is executed
Final result

Analysis:First, the results of Example 1 and Example 2 are obvious. When an exception is encountered, directly enter the matching catch block, then continue to execute the finallly statement block, and finally return the return result.

The second case:there is a return in the try block, but no exception is caught

Example 3:

Thinking:In the following code, there is a return statement in the try statement block, so do you directly return the exit method after executing the try statement block?

public static void main(String[]args) {
  String result = handleException3();
  System.out.println(result);
}
private static String handleException3() {
  try{
      System.out.println("");
    return "The return value of the try block";
  }catch(Exception e){
    System.out.println("Exception caught");
  }finally {
    System.out.println("finally block execution completed");
  }
  return "Final result";
}

The execution result of Example 3 is as follows:

Finally the block is executed
Return value of try block

Analysis:The result of Example 3 can actually look at the specific execution flow of the program by way of a breakpoint. Through the breakpoint we can find that the code first executes the code in the try block, when When the return statement is executed, the handleException3 method does not end immediately, but continues to execute the code in the finally block. After the code in the finally block is executed, it returns to the return statement of the try block, and then returns the final result. The handleException method is executed.

The third case:return in both try block and finally

Example 4:

public static void main(String[]args) {
    System.out.println(handleException4());
  }

  /**
   * Case 3:return in both try and finally
   * @return
   */
  private static String handleException4() {
    try{
      System.out.println("");
      return "The return value of the try block";
    }catch(Exception e){
      System.out.println("Exception caught");
    }finally {
      System.out.println("finally block execution completed");
      return "finally return value";
    }
  //return "Final result";//No more return value
  }

Execution result of Example 4:

Finally the block is executed
Finally the return value

Analysis:It should be noted that when there is a return in the try block and finally, the return keyword is not allowed outside the try/catch/finally syntax block. Let's take a look at the specific execution flow of the code by interrupting points in the program. The code first executes the code in the try block. When the return statement is executed, the handleException4 method does not end immediately, but continues to execute the code in the finally block. When the return in the finally block is found, the return in the finally block is returned directly. The value(that is, the final result) is returned, and the handleException4 method is executed.

Fourth case:try block, catch block, finally block all have return

Example 5:

public static void main(String[]args) {
    System.out.println(handleException5());
  }

  /**
   * Case 4:try, catch, finally all have return
   * @return
   */
  private static String handleException5() {
    try{
      System.out.println("try start");
      int[]array = {1, 2, 3};
      int i = array[10];
      System.out.println("try end");
      return "The return value of the try block";
    }catch(Exception e){
      e.printStackTrace();//This line of code is actually to print out the specific information of the exception
      System.out.println("Exception caught");
      return "Catch's return value";
    }finally {
      System.out.println("finally block execution completed");
      return "finally return value";
    }
//return "Final result";
  }

Execution result of Example 5:

try to start
Exception caught
Finally the block is executed
Finally the return value
java.lang.ArrayIndexOutOfBoundsException:10

at com.example.javabasic.javabasic.ExceptionAndError.TryCatchFinally.handleException5(TryCatchFinally.java:25)
at com.example.javabasic.javabasic.ExceptionAndError.TryCatchFinally.main(TryCatchFinally.java:14)

Analysis:The program first executes the code in the try block. If an exception is found in the try block, the code behind the try block will not be executed(naturally, it will not return), then enter the catch block that matches the exception, and then enter the catch The code is executed in the block. When the return statement in the catch is executed, the program will not terminate immediately, but will continue to execute the code in the finally block, and finally execute the return in the finally, and then return the final result of the return.

to sum up

In fact, we can find through the above example that no matter where the return keyword is, finally will definitely be executed. Theoretically speaking, the return keyword is allowed to be written in the try, catch, and finally blocks, but the return value defined by the return keyword in the block with a lower execution priority will override the return keyword defined in the return keyword in the block with a higher execution priority. value. In other words, the return value defined in the finally block will override the return value defined in the catch block and the try block; the return value defined in the catch block will override the return value defined in the try block.
In other words, if the return value is defined by the return keyword in the finally block, then all the previous return values defined by the return keyword will be invalid-because the code in the finally block must be executed.


Finally, recently, many friends asked me for a Linux learning roadmap, so I used my spare time to stay up all night in my spare time and put together an e-book. Whether you are interviewing or self-improving, I believe it will help you!

Free for everyone, just ask everyone to give me a thumbs up!

EBook | Linux Development Learning Roadmap

I also hope that some friends can join me and make this e-book more perfect!

Harvest? I hope the veterans will have a three-match strike to show this article to more people.

Recommended reading: