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"); } } }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)In addition, if the comments in the above example are removed, the execution result is:
return value of test(): 0In 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"); } } }
Demo2 are as follows:
try block
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"); } } }
The execution result of Demo3 is:
try block finally block
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"); } } }
The execution result of Demo4 is:
try block exception block finally block reture value of test() : 2
Demo4 illustrates that the finally statement block is executed before the return statement in the catch statement block.
##
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; } } }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++; } } }# The execution result of ##Demo6 is:
return value of getValue(): 1
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.
try{ return expression; }finally{ do some work; }
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;
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; } } }
Demo7的执行结果为:
return value of getValue(): 5
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; } }
Demo8的执行结果为:
return value of getValue(): 5
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"; } }
Demo9的执行结果为:
try block return statement finally block after return
总结:
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!

C语言return的用法有:1、对于返回值类型为void的函数,可以使用return语句来提前结束函数的执行;2、对于返回值类型不为void的函数,return语句的作用是将函数的执行结果返回给调用者;3、提前结束函数的执行,在函数内部,我们可以使用return语句来提前结束函数的执行,即使函数并没有返回值。

Java中final、finally、finalize的区别,需要具体代码示例在Java编程中,经常会遇到final、finally、finalize这三个关键词,它们虽然拼写相似,但却有不同的含义和用法。本文将详细解释这三个关键词的区别,同时给出代码示例以帮助读者更好地理解。一、final关键字final关键字可以用于类、方法和变量。它的作用是使被修饰的类

源码:publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#输出上述代码的输出可以简单地得出结论:return在finally之前执行,我们来看下字节码层面上发生了什么事情。下面截取case1方法的部分字节码,并且对照源码,将每个指令的含义注释在

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Vue3.2setup语法糖是在单文件组件(SFC)中使用组合式API的编译时语法糖解决Vue3.0中setup需要繁琐将声明的变量、函数以及import引入的内容通过return向外暴露,才能在使用的问题1.在使用中无需return声明的变量、函数以及import引入的内容,即可在使用语法糖//import引入的内容import{getToday}from'./utils'//变量constmsg='Hello!'//函数func


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool