直接来自这个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 得到尊重,而在显式调用时却没有?