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.
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.
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();
}
}
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.