What happens if an exception is thrown during fina

2019-06-21 15:36发布

问题:

What would happen if an exception is thrown during the execution of finalize()? Is the stack unwind like normally? Does it continue finalize() and ignore the exception? Does it stop finalize() and continue GC the object? Or something else?

I'm not looking for guidelines of using finalize() there are plently of pages explaining that.

回答1:

From the Object#finalize() javadoc:

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.



回答2:

The correct way to code a finalizer, assuming you have a valid reason to write one at all, is this:

protected void finalize() throws Throwable
{
  try
  {
    // my finalization code
  }
  finally
  {
    super.finalize();
  }
}


回答3:

In case if exception would be thrown, then the invocation of finalize will be terminated, and next time it will not be invoked but object will be GC-ed from memory.