TIL-18: Prefer try-with-resources to try-catch-finally

Recep İnanç
2 min readDec 14, 2019
Photo by Mike from Pexels

“Today I learned try-with-resources should be used over try-catch-finally when we work with resources.”

TL;DR

Always use try-with-resources statement instead of try-catch-finally when working with resources that need to be closed, for a cleaner, shorter, better code and better exception management.

Why?

In java, we often use try-finally for cases where we need to manually close a resource (i.e. InputStream, OutputStream, etc.).

The main problem with this approach is that if you get an error while in the try part of your open InputStream, and you get an error rather than opening the stream like you get an error because you tried to run .readLines(), and because of the same reason the code in your finally part, .close(), fails and throws an Exception, you will not be able to view the first exception. This gives you a hard time when debugging is required in such cases.

When Java 7 introduced try(withResources) that solves this problem. Your resource needs to implement an AutoClosable interface, and then the latter exceptions are suppressed and the first one is thrown. It also allows you to still access all of the suppressed exceptions, even programmatically using getSuppressed().

Sample code for “try-catch-finally replaced by try-with-resources”

Resources

Effective Java, 3rd Edition — Chapter 2, Item 9

Cheers!

--

--

Recep İnanç

Software Developer @Amazon. You can find me at recepinanc.com. My opinions are my own.