Try-with-Resources: Automatic Resource Deallocation - Java Language Basics

Java examples for Language Basics:try with Resources

Introduction

The try-with-resources statement simplifies resources releasing in a corresponding finally block.

The general form of a try-with-resources statement is

try (ClassName theObject = new ClassName()) 
{ 
  // use theObject here 
} 
catch (Exception e) 
{ 
  // catch exceptions that occur while using the resource   
} 

where ClassName is a class that implements the AutoCloseable interface.

The try-with-resources statement implicitly calls the theObject's close method at the end of the try block.

You can allocate multiple re-sources in the parentheses following try by separating them with a semicolon ;.


Related Tutorials