gpt4 book ai didi

java - 在什么情况下 finally {} block 不会执行?

转载 作者:IT老高 更新时间:2023-10-28 21:03:18 25 4
gpt4 key购买 nike

在 Java try{} ... catch{} ... finally{} block 中,finally{} 中的代码通常被认为是“保证”无论 try/catch 中发生什么,都运行。但是,我知道它至少不会执行的两种情况:

  • 如果 System.exit(0) 被调用;或者,
  • 如果异常一直抛出到 JVM 并且发生默认行为(即,printStackTrace() 并退出)

是否有任何其他程序行为会阻止 finally{} block 中的代码执行?代码会在什么特定条件下执行?

编辑: 正如 NullUserException 所指出的,第二种情况实际上是不正确的。我认为这是因为标准错误中的文本在标准输出之后打印,防止在不向上滚动的情况下看到文本。 :) 抱歉。

最佳答案

如果您调用 System.exit()程序立即退出,没有调用 finally

JVM 崩溃,例如Segmentation Fault,也会阻止 finally 被调用。即 JVM 在此时立即停止并生成崩溃报告。

无限循环也会阻止 finally 被调用。

finally block 总是在抛出 Throwable 时调用。即使您调用 Thread.stop() 触发 ThreadDeath被扔到目标线程中。这可以被捕获(它是一个 Error)并且 finally block 将被调用。


public static void main(String[] args) {
testOutOfMemoryError();
testThreadInterrupted();
testThreadStop();
testStackOverflow();
}

private static void testThreadStop() {
try {
try {
final Thread thread = Thread.currentThread();
new Thread(new Runnable() {
@Override
public void run() {
thread.stop();
}
}).start();
while(true)
Thread.sleep(1000);
} finally {
System.out.print("finally called after ");
}
} catch (Throwable t) {
System.out.println(t);
}
}

private static void testThreadInterrupted() {
try {
try {
final Thread thread = Thread.currentThread();
new Thread(new Runnable() {
@Override
public void run() {
thread.interrupt();
}
}).start();
while(true)
Thread.sleep(1000);
} finally {
System.out.print("finally called after ");
}
} catch (Throwable t) {
System.out.println(t);
}
}

private static void testOutOfMemoryError() {
try {
try {
List<byte[]> bytes = new ArrayList<byte[]>();
while(true)
bytes.add(new byte[8*1024*1024]);
} finally {
System.out.print("finally called after ");
}
} catch (Throwable t) {
System.out.println(t);
}
}

private static void testStackOverflow() {
try {
try {
testStackOverflow0();
} finally {
System.out.print("finally called after ");
}
} catch (Throwable t) {
System.out.println(t);
}
}

private static void testStackOverflow0() {
testStackOverflow0();
}

打印

finally called after java.lang.OutOfMemoryError: Java heap space
finally called after java.lang.InterruptedException: sleep interrupted
finally called after java.lang.ThreadDeath
finally called after java.lang.StackOverflowError

注意:在每种情况下,线程都会继续运行,即使在 SO、OOME、Interrupted 和 Thread.stop() 之后也是如此!

关于java - 在什么情况下 finally {} block 不会执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12430642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com