Exception Handling – Throwing an Exception Inside Finally Block

coding-styleexception handlingexceptions

Static code analyzers like Fortify "complain" when an exception might be thrown inside a finally block, saying that Using a throw statement inside a finally block breaks the logical progression through the try-catch-finally. Normally I agree with this. But recently I've come across this code:

SomeFileWriter writer = null; 
try { 
     //init the writer
     //write into the file
} catch (...) {
     //exception handling
} finally {
     if (writer!= null) writer.close();  
}

Now if the writer cannot be closed properly the writer.close() method will throw an exception. An exception should be thrown because (most probably) the file wasn't saved after writing.

I could declare an extra variable, set it if there was an error closing the writer and throw an exception after the finally block. But this code works fine and I'm not sure whether to change it or not.

What are the drawbacks of throwing an exception inside the finally block?

Best Answer

Basically, finally clauses are there to ensure proper release of a resource. However, if an exception is thrown inside the finally block, that guarantee goes away. Worse, if your main block of code throws an exception, the exception raised in the finally block will hide it. It will look like the error was caused by the call to close, not for the real reason.

Some people follow a nasty pattern of nested exception handlers, swallowing any exceptions thrown in the finally block.

SomeFileWriter writer = null; 
try { 
     //init the writer
     //write into the file
} finally {
    if (writer!= null) {
        try {
            writer.close();
        } catch (...) {
            // swallow
        }
    }
}

In older versions of Java, you can "simplify" this code by wrapping resources in classes that do this "safe" clean up for you. A good friend of mine creates a list of anonymous types, each that provide the logic for cleaning up their resources. Then his code simply loops over the list and calls the dispose method within the finally block.

Related Topic