如果调用
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()之后,线程仍保持运行状态!



