In Rational Application Developer(RAD based on eclipse), under software analyzer, I see a code review comment (under Performance =>Memory section) saying "Avoid the throw statement inside of finally".
How does defining throw inside a finally block affect performance?
Here is code snippet, we have already suggested to change code to log exception trace and do not throw exception,
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException ex) {
throw ex;
}
}
}
I was just wondering how this could affect memory and performance?
The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.
Methods invoked from within a finally block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire try block.
The finally block executes regardless of whether an exception is thrown or caught.
An exception thrown from the finally
block will replace any exception that was thrown from the try
, and information about the real problem is likely to be lost.
Since the try-finally
block is allowed to throw an IOException
in this case, here's a better way to write it:
try (BufferedReader bufferedReader = Files.newBufferedReader(Paths.get("file.txt"))) {
/* Work with `bufferedReader` */
}
This automatically closes the reader when the block exits, and handles any resulting exceptions nicely, even if the code inside the try
block throws its own exception first, using the "suppression" mechanism of Throwable
.
If the try
block completes without exception, the result will be the result of closing the resource (exception or not). If the try
block throws an exception, that will be the exceptional result. But if the close()
method raises an exception too, it will be added to the try
block's exception as a "suppressed" exception. You can interrogate it programmatically, and when the stack trace is printed, the suppressed exception will be displayed, much like the "caused by" exceptions you may be more familiar with.
And, you can try-with-multiple resources; these will all be closed, and multiple closure exceptions can be suppressed.
This assumes you're using file I/O, but the same "try-with-resources" structure will work on anything that implements AutoCloseable
(streams, SQL objects, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With