The try-with-resources statement

Govinda Raj
2 min readJan 25, 2018

--

You must have come across Exception Handling paradigm while you were developing an application. So what’s an Exception?

Exception — Unwanted Event, Undesirable obstruction, Event need to be handled.

If we talk in terms of OOPs, then an exception is a class which tells us about error which occurred while execution of the application or while application is already running.

What do I mean when I say exceptional circumstances?

Well, I mean that when your code is running, something can happen. For example, let’s say we specify that we want Java to read some information from a file. We specify the filename and we try to “open” the file.
Well, what happens if that file doesn’t exist (perhaps it was moved from the expected location during the time that the program was running). Well, the code will complain! Java will throw an exception.

If you told Java to “open” a file at a specific location and that file doesn’t exist, what the heck should the code do now?!

Well, thankfully there’s a way for us to do something in the event of a problem in our code.

Try-with-resources (introduced in Java 7) is a new exception handling mechanism that makes it easier to correctly close resources that are used within a try-catch block.

Let’s talk about “try-with-resources Statement”.

The try-with-resources statement is a try statement that declares one or more resources.
A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

You may declare one or more resources in a try-with-resources statement.
The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

Thanks for reading!

You can reach me on Linkedin — Govinda Raj

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Govinda Raj
Govinda Raj

Written by Govinda Raj

Senior Software Developer. Tech Enthusiast and love coding. My portfolio: https://govinda-raj.github.io/

No responses yet

Write a response