Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Try with resources

How does the compiler know that you are using try-with resources and not the old fashioned try-catch-finally block, since you didn't explicitly implement the AutoCloseable interface?

3 Answers

Hi Colin,

try {} //standard try block

try(resourceGoesHere){} //try with resources

The resource that must be closed once the program is done with it is declared in parentheses.

Hope that helps!

Thank you very much, Evan. It definitely helps. What about the AutoCloseable interface? Is it actually being implemented here? I'm also confused about that.

Resources are objects which implement the AutoCloseable interface. The resource is what handles the required step of implementing the interface and defining the behavior of close(), the function that's run when the try-with-resources is finished; you'd only have to handle the implementation if the resource was one of your own creation that was a child of an object that didn't already implement AutoCloseable, or if you wanted to change the behavior of close() for some specific purpose.

Wow! Thanks very much. This clears things up nicely for me.