Home Java javaTutorial The execution order of try, finally and return statements in Java

The execution order of try, finally and return statements in Java

Aug 23, 2017 am 10:19 AM
finally java return

This article mainly introduces a brief analysis of the execution sequence of the try finally return statement in Java. Friends in need can refer to it

Problem Analysis

Will the finally statement block be executed?

Perhaps the first reaction of many people is that they will definitely implement it, but if they think about it carefully, if they will definitely implement it, they will not ask such SB.

Demo1


##

public class Test {
  public static void main(String[] args) {
    System.out.println("return value of test(): " + test());
  }
  public static int test() {
    int i = 1;
    // if (i == 1) {
    // return 0;
    // }
    System.out.println("the previous statement of try block");
    i = i / 0;
    try {
      System.out.println("try block");
      return i;
    } finally {
      System.out.println("finally block");
    }
  }
}
Copy after login

The execution results of Demo1 are as follows:


the previous statement of try block
Exception in thread "main" java.lang.ArithmeticException: / by zero
  at com.becoda.bkms.bus.basics.web.Test2.test(Test2.java:15)
  at com.becoda.bkms.bus.basics.web.Test2.main(Test2.java:5)
Copy after login

In addition, if the comments in the above example are removed, the execution result is:


return value of test(): 0
Copy after login

In the above two cases, the finally statement block is not executed. What problem does it explain? The finally statement block will be executed only when the try statement block corresponding to the finally statement block is executed. However, the above all return (return) or throw an exception before the try statement block, so the finally statement block corresponding to the try statement is not executed. So, even if the try statement block corresponding to finally is executed, will the finally statement block definitely be executed? But the execution results of the following example

Demo2

##

public class Test {
  public static void main(String[] args) {
    System.out.println("return value of test(): " + test());
  }
  public static int test() {
    int i = 1;
    try {
      System.out.println("try block");
      System.exit(0);
      return i;
    } finally {
      System.out.println("finally block");
    }
  }
}
Copy after login

Demo2 are as follows:

try block
Copy after login

The finally statement block is still not executed, why? Because we executed the System.exit(0) statement in the try statement block, terminating the running of the Java virtual machine, although under normal circumstances we would not do this. There is also a situation where when a thread is interrupted (interrupted) or terminated (killed) while executing a try statement block or catch statement block, the corresponding finally statement block may not be executed. There is also a more extreme situation, that is, when the thread is running a try statement block or a catch statement block, it suddenly crashes or loses power, and the finally statement block will definitely not be executed.

Finally statement example explanationLet’s look at a simple example

Demo3

public class Test {
  public static void main(String[] args) {
    try {
      System.out.println("try block");
      return;
    } finally {
      System.out.println("finally block");
    }
  }
}
Copy after login

The execution result of Demo3 is:

try block
finally block
Copy after login

Demo3 explains that the finally statement block is in the try statement block executed before the return statement in . Let's look at another example.

Demo4

##
public class Test {
  public static void main(String[] args) {
    System.out.println("reture value of test() : " + test());
  }
  public static int test() {
    int i = 1;
    try {
      System.out.println("try block");
      i = 1 / 0;
      return 1;
    } catch (Exception e) {
      System.out.println("exception block");
      return 2;
    } finally {
      System.out.println("finally block");
    }
  }
}
Copy after login

The execution result of Demo4 is:

try block
exception block
finally block
reture value of test() : 2
Copy after login

Demo4 illustrates that the finally statement block is executed before the return statement in the catch statement block.

From Demo3 and Demo4 above, we can see that the finally statement block is actually executed before the return statement in try or catch. More generally, the finally statement block should be executed before the control transfer statement. Before execution, in addition to return, the control transfer statement also includes break and continue.

Let’s look at the following two examples

Demo5

##

public class Test {
  public static void main(String[] args) {
    System.out.println("return value of getValue(): " + getValue());
  }
  public static int getValue() {
    try {
      return 0;
    } finally {
      return 1;
    }
  }
}
Copy after login

Execution of Demo5 The result is:


return value of getValue(): 1

Demo6

public class Test {
  public static void main(String[] args) {
    System.out.println("return value of getValue(): " + getValue());
  }
  public static int getValue() {
    int i = 1;
    try {
      return i;
    } finally {
      i++;
    }
  }
}
Copy after login
# The execution result of ##Demo6 is:


return value of getValue(): 1
Copy after login

Using the conclusion drawn from our above analysis: the finally statement block is executed before the return statement in try or catch. From this, we can easily understand that the execution result of Demo5 is 1. Because the return 1; statement in finally is executed before the return 0; statement in try, then after the return 1; statement in finally is executed, the control of the program is transferred to its caller main() function and returns The value is 1. So why is the return value of Demo6 not 2, but 1? According to the analysis logic of Demo5, the i++; statement in finally should be executed before return i; in try? The initial value of i is 1, then execute i++; then it is 2, and then execute return i; shouldn't it be 2? How did it become 1?

To explain this problem, you need to understand how the Java virtual machine compiles the finally statement block.

Java methods are executed in stack frames. The stack frame is the unit of the thread's private stack. The thread executing the method will allocate a small space for each method as the memory space when the method is executed. The stack frame Divided into three areas:

1. Operand stack, used to save the operands in the expression being executed

2. Local variable area, used to save variables used in the method , including method parameters, variables declared inside the method, and member variables of the object or class member variables (static variables) used in the method. The last two variables will be copied to the local variable area, so in a multi-threaded environment, these A variable needs to be declared as a volatile type as needed

3, bytecode instruction area

For example, the following code

try{
  return expression;
}finally{
  do some work;
}
Copy after login

First We know that finally statements will definitely be executed, but what is their execution order? Their execution order is as follows:

1. Execution: expression, calculate the expression, and the result is saved on the top of the operand stack;

2. Execution: the top value of the operand stack (the result of expression ) is copied to the local variable area as the return value;

3、执行:finally语句块中的代码;

4、执行:将第2步复制到局部变量区的返回值又复制回操作数栈顶;

5、执行:return指令,返回操作数栈顶的值;

我们可以看到,在第一步执行完毕后,整个方法的返回值就已经确定了,由于还要执行finally代码块,因此程序会将返回值暂存在局部变量区,腾出操作数栈用来执行finally语句块中代码,等finally执行完毕,再将暂存的返回值又复制回操作数栈顶。所以无论finally语句块中执行了什么操作,都无法影响返回值,所以试图在finally语句块中修改返回值是徒劳的。因此,finally语句块设计出来的目的只是为了让方法执行一些重要的收尾工作,而不是用来计算返回值的。

这样就能解释Demo6的问题了

让我们再来看以下 3 个例子。

Demo7


public class Test {
  public static void main(String[] args) {
    System.out.println("return value of getValue(): " + getValue());
  }
  @SuppressWarnings("finally")
  public static int getValue() {
    int i = 1;
    try {
      i = 4;
    } finally {
      i++;
      return i;
    }
  }
}
Copy after login

Demo7的执行结果为:


return value of getValue(): 5
Copy after login
Copy after login

Demo8


public class Test {
  public static void main(String[] args) {
    System.out.println("return value of getValue(): " + getValue());
  }
  public static int getValue() {
    int i = 1;
    try {
      i = 4;
    } finally {
      i++;
    }
    return i;
  }
}
Copy after login

Demo8的执行结果为:


return value of getValue(): 5
Copy after login
Copy after login

Demo9


public class Test {
  public static void main(String[] args) {
    System.out.println(test());
  }
  public static String test() {
    try {
      System.out.println("try block");
      return test1();
    } finally {
      System.out.println("finally block");
    }
  }
  public static String test1() {
    System.out.println("return statement");
    return "after return";
  }
}
Copy after login

Demo9的执行结果为:


try block
return statement
finally block
after return
Copy after login

总结:

1、finally 语句块不一定会被执行

2、finally 语句块在 try 语句块中的 return 语句之前执行

3、finally 语句块在 catch 语句块中的 return 语句之前执行

4、finally 语句块中的 return 语句会覆盖 try 块中的 return 返回

5、试图在 finally 语句块中修改返回值不一定会被改变

The above is the detailed content of The execution order of try, finally and return statements in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles