What happens if an exception is thrown during finalize()
Asked Answered
C

3

5

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.

Chiefly answered 14/6, 2010 at 14:51 Comment(0)
R
9

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.

Redaredact answered 14/6, 2010 at 14:53 Comment(2)
Completely unrelated to the question, but ... I LOVE YOUR AVATAR. Grim Fandango was the greatest game EVAR!Empyreal
Manuel has definitely been finalized.Barbados
S
4

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();
  }
}
Sirius answered 15/6, 2010 at 7:17 Comment(0)
S
1

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.

Scoreboard answered 6/3, 2012 at 19:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.