Module 8 · Exceptions and File Handling — topic 2 of 3
Custom Exceptions and try-with-resources
Designing your own exception classes, checked versus unchecked custom exceptions, chaining causes, AutoCloseable and try-with-resources, and suppressed exceptions.
Learning objectives
- Create checked and unchecked custom exceptions
- Wrap low-level exceptions while preserving the cause
- Use try-with-resources to close resources reliably
Definition
A custom exception is a class that extends Exception (checked) or RuntimeException (unchecked) to represent a domain-specific error. try-with-resources automatically closes objects implementing AutoCloseable when the block ends.
Introduction
IllegalArgumentException("insufficient funds") works, but callers can't distinguish it from any other bad argument. An InsufficientFundsException that carries the balance and the requested amount lets them react precisely. And because resources such as files and database connections must always be closed, Java provides try-with-resources to do it for you.
Why it matters
Meaningful exception types make APIs self-documenting and error handling precise.
Forgetting to close files and connections leaks resources; try-with-resources makes that impossible.
Detailed explanation
Defining one. Extend Exception for a checked exception (callers must handle it) or RuntimeException for an unchecked one. Provide constructors that take a message and, ideally, a cause: super(message, cause).
Choosing checked or unchecked. Use checked exceptions for recoverable conditions the caller should consider (a payment is declined, a file is missing). Use unchecked exceptions for programming errors and invalid arguments. Many modern libraries prefer unchecked exceptions to keep code concise.
Extra data. Add fields (the requested amount, the invalid value) and getters, so handlers can act on the details rather than parsing messages.
Chaining. When translating a low-level exception into a higher-level one, pass the original as the cause: throw new ReportException("cannot load report", e);. The stack trace then shows both, and getCause() retrieves the original.
try-with-resources (Java 7). try (var r = new Resource()) { ... } calls r.close() automatically when the block ends, whether normally or by an exception. Several resources are closed in reverse order of opening. Any class implementing AutoCloseable (or Closeable) works.
Suppressed exceptions. If the body throws and close() also throws, the body's exception is the one propagated and the close exception is attached to it as *suppressed* — available through getSuppressed().
Syntax
- Name exception classes with an Exception suffix.
- Always keep the original exception as the cause when wrapping.
- Resources declared in try(...) are effectively final.
Code examples
A checked custom exception with data
spent 200, left 300 cannot spend 450, only 300 available -> top up at least 150
try-with-resources closes in reverse order
open database open log file working with database and log file close log file close database done
More examples
Chaining causes and suppressed exceptions
Error: could not load report sales-2026 Caused by: NumberFormatException: For input string: "abc" Primary: query failed Suppressed: close failed too
Step-by-step explanation
parseRowfails with a low-level NumberFormatException for the text "abc".loadcatches it and throws a domain-level ReportException, passing the original as the cause.- The handler in
mainreports the high-level message and inspectsgetCause()for details. - In the second try,
query()throws, and then the automaticclose()throws too. - Java propagates the original exception ("query failed") and attaches the close failure as a suppressed exception instead of losing either one.
Expected output
Running “Chaining causes and suppressed exceptions” prints exactly:
Practical applications
- Domain errors such as OrderNotFoundException or PaymentDeclinedException in business services
- Wrapping SQLException or IOException in application-level exceptions
- Closing files, sockets, database connections and locks with try-with-resources
Best practices
- Create custom exceptions only when callers need to distinguish them.
- Always chain the cause when wrapping exceptions.
- Use try-with-resources for anything that implements AutoCloseable.
Common mistakes
Losing the original cause
Avoid
Prefer
Without the cause, the stack trace no longer shows what actually went wrong in the database.
Closing resources manually
Avoid
Prefer
If process throws, the manual close never runs; try-with-resources always closes.
Important notes
java.io.UncheckedIOExceptionis a ready-made unchecked wrapper for IOException.- Since Java 9, an existing effectively-final variable can be used directly:
try (reader) { ... }.
Key takeaways
- Extend Exception for checked and RuntimeException for unchecked custom exceptions.
- Pass the original exception as the cause when translating it.
- try-with-resources closes resources automatically, in reverse order, and records suppressed exceptions.
Try it yourself
- 1Create an
InvalidGradeExceptionand use it in a method that converts marks to grades. - 2Write a
Timerclass implementing AutoCloseable that prints how long its block took.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
5 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerTo create a checked custom exception, which class do you extend?
- BeginnerWhat is printed?
- ModerateWhat is printed?