栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在什么情况下,finally {}块将不执行?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在什么情况下,finally {}块将不执行?

如果调用

System.exit()
,程序将立即退出而不
finally
被调用。

JVM崩溃(例如分段错误)也将阻止最终被调用。也就是说,JVM此时会立即停止并生成崩溃报告。

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

当抛出Throwable时,总是调用finally块。即使您调用Thread.stop()

ThreadDeath
也会触发将a
引发到目标线程中。可以捕获到它(是
Error
),并会调用finally块。


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 spacefinally called after java.lang.InterruptedException: sleep interruptedfinally called after java.lang.ThreadDeathfinally called after java.lang.StackOverflowError

注意:在每种情况下,即使在SO,OOME,Interrupted和Thread.stop()之后,线程仍保持运行状态!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569213.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号