【发布时间】:2013-09-08 13:04:05
【问题描述】:
直接来自这个API:
如果 finalize 方法抛出未捕获的异常, 异常被忽略并且该对象的终结终止。
我尝试在按如下方式重写 finalize() 后显式调用它:
public void finalize() //
{
System.out.println("Garbage Collected");
throw new RuntimeException();
}
当我明确地调用它时,虽然我确实得到了异常,但另一方面,如果我隐含地让它消失,它会按预期忽略异常:
public static void main (String []args) throws Exception
{
B b = new B();
b=null;// LINE 3
System.gc(); // It prints "Garbage Collected" and do not throw the exception
//if it was b.finalize() instead of System.gc() and line 3 was commented out it would print Garbage Collected and then would throw the exception.
为什么会这样?为什么在第一种方式中使用System.gc() API 得到尊重,而在显式调用时却没有?
【问题讨论】:
-
直接来自 API:当垃圾收集器确定不再有对该对象的引用时,由垃圾收集器调用。
标签: java garbage-collection finalize