This repository contains all the code examples from the Try with Resources tutorial.
Read the complete tutorial with detailed explanations here:
https://www.javapro.academy/try-with-resources-tutorial/
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
- Java 9 or higher
- Maven (for dependency management)
Clone the repository:
git clone <your-repo-url>
cd try-with-resourcesInstall dependencies:
mvn clean installRun any example from your IDE (IntelliJ IDEA, Eclipse, VS Code) or command line:
java -cp target/classes blog.academy.javapro.TryWithResourcesBasicsrc/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
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)
Visit JavaPro Academy for more Java tutorials and courses:
https://www.javapro.academy/
Last Updated: January 21, 2026