在Java方法中的return语句之后,finally块会执行吗?
是的,即使在方法中的return语句之后,也会执行finally块。
即使Java中发生了异常,finally块也将始终执行。如果我们在 finally块中显式调用System.exit()方法,则仅将不执行它。在极少数情况下,finally将不会执行,例如JVM崩溃,电源故障,软件崩溃等。除这些条件外,finally块将始终执行。
示例
public class FinallyBlockAfterReturnTest {
public static void main(String[] args) {
System.out.println(count());
}
public static int count() {
try { return 1; } catch(Exception e) { return 2; } finally {
System.out.println("Finally block will execute even after a return statement in a method");
}
}
}输出结果
Finally block will always excute even after a return statement in a method 1
热门推荐
10 分别发的祝福语简短
11 大外甥高考祝福语简短
12 小学毕业校长简短祝福语
13 搞工程发财祝福语简短
14 冬季祝福语男生文案简短
15 同事生子问候祝福语简短
16 退休文案寄语简短祝福语
17 送给自己的祝福语简短
18 简短祝福语毛笔字