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.
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
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
| Habit | Why |
|---|---|
| Handle it or let it go up | either the catch deals with it, or the method declares throws |
| Never leave a catch empty | an empty catch hides the error |
| Catch the specific type | NumberFormatException, not a plain Exception |
| Prefer try-with-resources | Java 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.
StudyEasy AI Community
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
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.
