Intermediate level · Module 3: Exceptions and File Input/Output in Java · Lesson 2 of 3
Custom Exceptions and try-with-resources
Create exception types that describe your program's rules, and close files and other resources automatically.
In this lesson you will
- Create and throw a custom exception with a meaningful message
- Use try-with-resources to close readers and writers
Key concepts
custom exception classexception messageAutoCloseabletry-with-resources
The lesson
A custom exception names a rule of your program: class InsufficientFundsException extends Exception. Give it a constructor that passes a clear message to super. Callers can then catch exactly this problem and handle it differently from other errors.
Choose checked (extends Exception) when the caller can reasonably recover, such as a member who has reached their loan limit. Choose unchecked (extends RuntimeException) for errors that indicate a bug, such as an invalid argument from your own code.
Files, network connections and database connections must be closed. try (BufferedReader reader = Files.newBufferedReader(path)) { … } closes the reader automatically at the end, even if an exception is thrown. It replaces error-prone finally blocks.
Step by step
- Create LoanLimitException with a message constructor.
- Throw it from a lend() method when a member has three books.
- Catch it in the menu and show the message.
- Open a file with try-with-resources and read its first line.
Practice activity
Add a custom exception for every business rule in the wallet or library example and handle each one in the user interface.
Expected result: Each rule violation produces its own clear message, and no resources are left open.
Check your understanding
-
What does try-with-resources do?
Show answer
It closes the declared resources automatically when the block ends, even after an exception.
-
When should a custom exception be checked?
Show answer
When the caller can reasonably recover from it, such as a business rule being broken.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.