1

I just came across two contradictory sentences in the Java 8 Docs and wondered if there's anybody here who can clarify the real behaviour.

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

-> If I get it right, "uncaught exception" means, it is not caught by a try/catch - block, and this had nothing to do with whether it's a checked or unchecked exception.

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

-> That's exactly the opposite behaviour ... and what do they mean with "but is otherwise ignored" ? If it is not thrown by the finalize method... ?

Other people ask similar questions, e.g. other stackoverflow question, but the answer wasn't understandable.

I understand "halted" as paused - or is it the same thing as terminated?

By the way: I found out that it's actually bad practice to try to rely on finalize as there is no guarantee that it is ever called (even System.gc() does not force it and only suggests the compiler that garbage collection is needed). Some people recommend using a shutdown hook instead:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        // shutdown logic
    }
});

e.g. here stack overflow question

Still I think the Java docs should be clear and not state contradictory truths.... Or is this an English language problem...?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Nina
  • 681
  • 1
  • 10
  • 27

1 Answers1

1

The first sentence is misleading in its wordage, but they are the same statement.

The finalization "terminates" once the exception is thrown, meaning that the finalization is not properly completed.

Unlike a normal program where an uncaught exception could crash the entire program, if finalize throws an exception the program just moves on as normal.

Zircon
  • 4,677
  • 15
  • 32
  • So, the wording should be: "the exception will be ignored and the finalization of this object will be continued"? – Nina Jan 23 '17 at 21:13
  • Ok... so the program does not crash, and the finalize method will not be completed. Some clean-up stuff will not be done. But the program continues. – Nina Jan 23 '17 at 21:17
  • You see, the Garbage Collector calls finalize. If finalize **fails** and throws an exception, it (the Garbage Collector) catches the exception and ignores it. – alexbt Jan 23 '17 at 21:17