1.必然执行的异常统一处理出口(无论是否发生异常,finally必然执行)
2.return的时机
只有程序被关闭了,finally才不会被执行(这里的程序被关闭指的是软件在电脑中没了,电脑关机了)其他情况finally一定会被执行
public class Demo7 {
public static void main(String[] args) {
haha();
}
private static void haha(){
try {
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
return;
}catch (Exception e){
}finally {
System.out.println("汗滴禾下土");
}
}
}
Demo7的执行结果为1 2 3 4 汗滴禾下土
在这里return执行,需要准备返回值(这里因为是void没有返回值,所以这里return是准备了没有返回值的返回值)在准备返回值到方法结束中间,finally在这个时机被执行了
=============================================
public class Demo8 {
public static void main(String[] args) {
Person p = haha();
System.out.println(p.age);
}
public static Person haha(){
Person p = new Person();
try{
p.age = 18;
return p;
}catch (Exception e){
return null;
}
finally {
p.age = 28;
}
}
static class Person{
int age;
}
}
Demo8执行结果为28

=========================
try-catch-finally中,如果catch中return了,finally还会执行吗?
答:finally中的代码会执行
详解:
执行流程:
- 先计算返回值,并将返回值存储起来,等待返回
- 执行finally代码块
- 将之前存储的返回值,返回出去
需注意:
- 返回值是在finally运算之前就确定了,并且缓存了 ,不管finally对该值做任何的改变,返回的值都不会改变
- finally代码中不建议包含return,因为程序会在上述流程中提前退出,也就是说返回的值不是try或catch中的值
- 如果在try或catch中停止了JVM,则finally不会执行,例如停电关机,或通过如下代码退出JVM:System.exit(0);
==========================
public class Demo9 {
public static void main(String[] args) {
int a = haha();
System.out.println(a);
}
public static int haha(){
int a = 10;
try{
return a;//这里的a是新备份的一个a
}catch (Exception e){
return 0;
}
finally {
a = 20;//这里的a修改的不是备份的a
}
}
static class Person{
int age;
}
}
Demo9执行结果为10

========================
Demo8和Demo9的结果差异就是引用数据类型和非引用数据类型的差异
=========================
程序终止
public class Demo10 {
public static void main(String[] args) {
haha();
}
public static void haha(){
try{
int a = 10;
int b = 0;
System.out.println(a/b);
}catch (Exception e){
System.out.println("出现了异常");
//退出JVM,0表示正常退出,其他表示非正常退出
System.exit(0);
}finally {
System.out.println("锄禾日当午");
}
}
}
Demo10的结果为出现了异常,这里finally的程序没有执行
=========================================
public class Demo11 {
public static void main(String[] args) {
int a = haha();
System.out.println(a);
}
public static int haha(){
int a = 10;
int b = 0;
try{
System.out.println(a/b);
return 10;
}catch (Exception e){
return 0;
}finally {
return 20;
}
}
}
Demo11的结果为20,这是因为finally的程序一定会被执行,既然它return了一个数字,那么最后都会是它被最后返回出去
如果finally有return语句,永远返回finally中的结果
================================
本文详细探讨了Java中finally块的执行特性,包括其作为异常处理的统一出口,即使return也会执行finally,以及finally在不同场景下的返回值处理。文章通过多个示例演示了finally在return和异常情况下如何影响程序执行,强调了finally中的return语句可能导致返回值的变化,以及在特定情况下如系统退出或异常时finally可能不执行的情况。
1868

被折叠的 条评论
为什么被折叠?



