Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Exceptions

Java try-with-resources and Clean Error Handling

Put the resource in the brackets after try and Java closes it when the block ends. A LogFile that implements AutoCloseable prints Closed bills.log on success and, when share(90, 0) throws, before the catch runs. Plus four habits for clean errors.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Exceptions

What you will learn

  • Open a resource in the brackets after try so Java closes it for you
  • Explain the finally block Java adds behind the scenes
  • Make your own class closeable with AutoCloseable and trace when close() runs
  • Follow four habits for clean errors, including never leaving a catch empty

Before you start

  • Java exception handling: try, catch and finally
  • Java interfaces

Some code depends on something outside the program, like the keyboard or a file, and that thing has to be closed when you're done. With try-with-resources, Java does the closing for you, even when something goes wrong.

Open it in try ( )

package org.studyeasy.s03l21;

import java.util.Scanner;

public class Ex01_ScannerTwr {
    public static void main(String[] args) {
        // the Scanner is closed for you when this block ends
        try (Scanner in = new Scanner(System.in)) {
            System.out.print("Item: ");
            String item = in.nextLine();
            System.out.print("Quantity: ");
            int qty = in.nextInt();
            System.out.println(qty + " x " + item);
        }
    }
}
Item: Pasta
Quantity: 3
3 x Pasta

This is the Scanner from earlier, typed input Pasta and 3. The resource goes in the brackets right after try; that's what makes it try-with-resources. Inside the block you use it as normal. There's no in.close() anywhere: when the block ends, Java closes the Scanner, even if invalid input makes something throw.

Java writes the finally for you

On the left, what you write: try with LogFile log = new LogFile("bills.log") in brackets, one log.write line, and a closing brace. On the right, roughly what Java does: create the LogFile, start a normal try, run the same body, then a finally block that calls log.close(). You write try (LogFile log = new LogFile("bills.log")) { log.write("..."); } LogFile log = new LogFile("bills.log"); try { log.write("..."); } finally { log.close(); }
The closing brace is where the work happens: Java adds a finally that calls close().

The first line becomes two things: the resource is created, then a normal try starts. The body stays the same. At the closing brace, Java adds a finally block that calls close(). You don't write it, and nothing is left open. (This is a simplified view; the real version also handles a failing close.)

Make your own class closeable

package org.studyeasy.s03l21;

// AutoCloseable: Java can call close() for you
public class LogFile implements AutoCloseable {
    private final String name;

    public LogFile(String name) {
        this.name = name;
        System.out.println("Opened " + name);
    }

    public void write(String line) {
        System.out.println(name + ": " + line);
    }

    @Override
    public void close() {
        System.out.println("Closed " + name);   // runs even when the block fails
    }
}

The key part is implements AutoCloseable. It's one interface with one method, close. The constructor plays the opening and prints "Opened"; close does the clean-up. A real file writer works the same way. Anything that implements AutoCloseable can go in the brackets after try; delete the implements and try (LogFile log = ...) no longer compiles.

The block ends, close() runs

try (LogFile log = new LogFile("bills.log")) {
    log.write("Table 4 opened");
    log.write("Each pays " + share(120, 4));
}                                       // close() runs here, no call written
System.out.println("Table 4 done");
Opened bills.log
bills.log: Table 4 opened
bills.log: Each pays 30
Closed bills.log
Table 4 done

Look at the order. The constructor runs as the block starts, then the body (120 shared between 4 is 30). At the closing brace, Java calls close, and only then does the program carry on to "Table 4 done".

Even when it fails, it is closed

try (LogFile log = new LogFile("bills.log")) {
    log.write("Table 7 opened");
    log.write("Each pays " + share(90, 0));    // throws here
    log.write("Table 7 saved");                // never runs
} catch (ArithmeticException e) {
    System.out.println("Caught: " + e.getMessage());
}
Opened bills.log
bills.log: Table 7 opened
Closed bills.log
Caught: / by zero

share(90, 0) divides by zero before write even runs, so "Each pays" never prints, and Java leaves the block at the throw, so "Table 7 saved" doesn't either. The important part: "Closed bills.log" prints first, and only then does the catch run. On either path, close runs before anything after the block, and before the catch. Remove the catch and close still prints, then the program crashes with the stack trace.

Catch the exact failure

package org.studyeasy.s03l21;

public class Ex04_CleanErrors {
    public static void main(String[] args) {
        String[] guestCounts = {"4", "four"};      // typed in by staff
        for (String text : guestCounts) {
            try {
                int guests = Integer.parseInt(text);
                System.out.println("Table of " + guests);
            } catch (NumberFormatException e) {    // the exact failure, not Exception
                System.out.println("Skipped '" + text + "': " + e.getMessage());
            }
        }
    }
}
Table of 4
Skipped 'four': For input string: "four"

The catch names the exact type, NumberFormatException, not a plain Exception, and says what was skipped and why. Replace it with catch (Exception e) { } and "four" disappears without a word: nobody would know why that guest count was skipped.

Four habits for clean errors

HabitWhy
Handle it or let it go upeither the catch deals with it, or the method declares throws
Never leave a catch emptyan empty catch hides the error
Catch the specific typeNumberFormatException, not a plain Exception
Prefer try-with-resourcesJava adds the close, so nothing is left open; finally still works, but this is cleaner

To sum up: open the resource in the brackets after try, Java calls close when the block ends on success and on failure, and you catch the exact exception. For checked exceptions and throws, see throw, throws and custom exceptions.

Keep going in Java · 57 of 79

Previous
Java throw, throws, Checked vs Unchecked and Custom Exceptions
Next post
Java Generics: Type-Safe Containers
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Exception Handling: try, catch and finally

A bill splitter crashes on a table with zero guests and table 9 never runs. try and catch keep it going, the exception travels back through the call stack to the matching catch, two catches handle 0 and "four", and finally prints the receipt either way.

Java throw, throws, Checked vs Unchecked and Custom Exceptions

A deposit of -20 is fine for Java but wrong for the bank, so throw rejects it. An InsufficientFundsException declines Maria's 500 with "Short by 380.0", the stack trace shows withdraw, settle and main, and the compiler refuses a checked call nobody handles.

On this page

  • Open it in try ( )
  • Java writes the finally for you
  • Make your own class closeable
  • The block ends, close() runs
  • Even when it fails, it is closed
  • Catch the exact failure
  • Four habits for clean errors
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.