Java中的finally一定会被执行吗?
程序IT圈
共 7371字,需浏览 15分钟
·
2021-07-04 09:07
点击关注公众号,Java技术文及时送达
一、前言
二、finally一定会执行吗?
1.在执行try块之前直接return,我们发现finally块是不会执行的
public class TryCatchTest {
private static int total() {
int i = 11;
if (i == 11) {
return i;
}
try {
System.out.println("执行try");
} finally {
System.out.println("执行finally");
}
return 0;
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
输出结果:
执行main:11
复制代码
2.在执行try块之前制造一个错误,直接爆红
public class TryCatchTest {
private static int total() {
return 1 / 0;
try {
System.out.println("执行try");
} finally {
System.out.println("执行finally");
}
return 0;
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
public class TryCatchTest {
private static int total() {
try {
System.out.println("执行try");
System.exit(0);
} catch (Exception e) {
System.out.println("执行catch");
} finally {
System.out.println("执行finally");
}
return 0;
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
输出结果:
执行try
三、finally执行时机探讨
public class TryCatchTest {
private static int total() {
try {
System.out.println("执行try");
return 11;
} finally {
System.out.println("执行finally");
}
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
输出结果:
执行try
执行finally
执行main:11
public class TryCatchTest {
private static int total() {
try {
System.out.println("执行try");
return 1 / 0;
} catch (Exception e) {
System.out.println("执行catch");
return 11;
} finally {
System.out.println("执行finally");
}
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
输出结果:
执行try
执行catch
执行finally
执行main:11
四、finally块中的返回值
1.finally块不含返回值,但是做改变变量值的操作
public class TryCatchTest {
private static int total() {
int i = 0;
try {
System.out.println("执行try:" + i);
return i;
} finally {
++i;
System.out.println("执行finally:" + i);
}
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
输出结果:
执行try:0
执行finally:1
执行main:0
++i
使得i等于1
,在执行return i;
自然会返回1。2.finally中含有返回值
public class TryCatchTest {
private static int total() {
try {
System.out.println("执行try");
return 1;
} finally {
System.out.println("执行finally");
return 2;
}
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
输出结果:
执行try
执行finally
执行main:2
public class TryCatchTest {
private static int total() {
int i = 1;
try {
System.out.println("执行try:" + i);
return i;
} finally {
++i;
System.out.println("执行finally:" + i);
return i;
}
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
输出结果:
执行try:1
执行finally:2
执行main:2
public class TryCatchTest {
private static int total() {
int i = 1;
try {
System.out.println("执行try:" + i);
} finally {
++i;
System.out.println("执行finally:" + i);
}
return i;
}
public static void main(String[] args) {
System.out.println("执行main:" + total());
}
}
执行结果:
执行try:1
执行finally:2
执行main:2
如有文章对你有帮助,
欢迎关注❤️、点赞👍、转发📣!
评论