finally{}语句面试知识点总结
无论 try、catch语句中异常是否发生,除非电脑断电或程序不在内存中,finally语句必然执行。
案例一:
当test方法中的return语句执行后方法结束,finally语句还会不会执行
public class FinallyDemo {
public static void main(String[] args) {
test();
}
public static void test(){
try{
System.out.println("1");
return;
}catch(Exception e){
}finally{
System.out.println("finally语句已执行");
}
}
}
执行结果:
Connected to the target VM, address: '127.0.0.1:55869', transport: 'socket'
1
finally语句已执行
Disconnected from the target VM, address: '127.0.0.1:55869', transport: 'socket'
Process finished with exit code 0
原因:
finally的执行时间实际上是在return a语句的中间; test方法在准备return方法的返回结果时finally语句被执行。
特殊案例:
注意方法返回值为基本数据类型与引用数据类型之间的区别
引用类型:
public class FinallyDemo {
public static void main(String[] args) {
Persion p = test();
System.out.println(p.age);
}
public static Persion test() {
Persion p = new Persion();
try {
p.age = 18;
return p;
} catch (Exception e) {
return p;
} finally {
p.age = 28;
}
}
static class Persion {
int age;
}
}
执行结果:
Connected to the target VM, address: '127.0.0.1:56264', transport: 'socket'
28
Disconnected from the target VM, address: '127.0.0.1:56264', transport: 'socket'
Process finished with exit code 0
非引用类型:
public class FinallyDemo {
public static void main(String[] args) {
int a = test();
System.out.println(a);
}
public static int test() {
try {
int a= 10;
return a;
} catch (Exception e) {
return 0;
} finally {
int a= 20;
System.out.println("finally语句已执行");
}
}
}
结果:
Connected to the target VM, address: '127.0.0.1:56644', transport: 'socket'
finally语句已执行
10
Disconnected from the target VM, address: '127.0.0.1:56644', transport: 'socket'
Process finished with exit code 0