Java: impact of throwing an exception in finalize()

299 Views Asked by At

I am confused about this statement in Java Doc of Object#finalize():

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

Does or does not an exception thrown by the finalize() have impact in the finalization of an object?

1

There are 1 best solutions below

0
Holger On

The sentence

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

is indeed misleading. Strangely, there is a more precise sentence within the same documentation, shortly before it:

If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

So, it’s only about uncaught exceptions, not about exceptions thrown and caught within finalize() or a method invoked by finalize(). Further “halted” means “terminated”, not paused or blocked.

It gets clearer when considering that “finalization of an object” means “invoking its finalize() method”, not the reclamation of an object’s memory, which is entirely independent from that. So terminating the finalization is not a surprising behavior, as uncaught exceptions always terminate the current method execution. “Otherwise” means “besides terminating the current finalization”, indicating no other side effects, e.g. no logging and no effect on other objects’ finalization.

This differs from, e.g. having an infinite loop in a finalize() method. This may indeed block the dedicated thread, preventing the finalization of other objects.