Skip to content

The-Java-Bootcamp/try-with-resources

Repository files navigation

Try with Resources - Java Tutorial

This repository contains all the code examples from the Try with Resources tutorial.

Original Article

Read the complete tutorial with detailed explanations here:
https://www.javapro.academy/try-with-resources-tutorial/

What's Inside

This repository includes working Java examples demonstrating:

  • Traditional try-catch-finally approach vs try-with-resources
  • Basic try-with-resources usage
  • Multiple resources management
  • Custom AutoCloseable resources
  • Exception handling with suppressed exceptions
  • Resource closing order
  • Java 9 effectively final variables
  • Database operations with try-with-resources

Prerequisites

  • Java 9 or higher
  • Maven (for dependency management)

Running the Examples

Clone the repository:

git clone <your-repo-url>
cd try-with-resources

Install dependencies:

mvn clean install

Run any example from your IDE (IntelliJ IDEA, Eclipse, VS Code) or command line:

java -cp target/classes blog.academy.javapro.TryWithResourcesBasic

Project Structure

src/main/java/blog/academy/javapro/
├── CatchAndFinally.java
├── ClosingOrder.java
├── DatabaseOperations.java
├── EffectivelyFinal.java
├── MultipleResources.java
├── MyResource.java
├── ResourceFirst.java
├── ResourceSecond.java
├── ResourceWithException.java
├── TraditionalApproach.java
└── TryWithResourcesBasic.java

Code Examples

Each file demonstrates a specific aspect of try-with-resources:

  • TraditionalApproach.java - Old try-catch-finally pattern
  • TryWithResourcesBasic.java - Simple try-with-resources usage
  • MultipleResources.java - Managing multiple resources
  • MyResource.java - Custom AutoCloseable implementation
  • ResourceFirst.java & ResourceSecond.java - Used by ClosingOrder example
  • ClosingOrder.java - Demonstrates resource closing order
  • ResourceWithException.java - Exception handling with suppressed exceptions
  • CatchAndFinally.java - Using catch and finally with try-with-resources
  • EffectivelyFinal.java - Java 9 effectively final variables
  • DatabaseOperations.java - Real-world database example (requires H2 dependency)

Learn More

Visit JavaPro Academy for more Java tutorials and courses:
https://www.javapro.academy/

Last Updated: January 21, 2026