Exception Handling
Exceptions signal that something went wrong. Handling them well keeps programs stable and errors understandable.
On this page · 5 min · Intermediate
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 30, 2026
Related tutorials
In simple words#
try/catch is a safety net under a trapeze. If the performer slips (an exception), the net catches them and the show continues instead of ending in disaster.
- Checked exception
- Must be caught or declared (IOException).
- Unchecked exception
- RuntimeException subclasses (NullPointerException).
- try-with-resources
- Automatically closes files and connections.
Learning objectives#
- Catch and handle exceptions
- Distinguish checked and unchecked
- Throw and declare exceptions
- Close resources automatically
Explanation#
try { risky } catch (SpecificException e) { handle } finally { always runs }.
Checked exceptions (IOException, SQLException) must be caught or declared with throws. Unchecked ones (extend RuntimeException) usually mean programming errors.
throw new IllegalArgumentException("...") signals invalid input. Custom exceptions express business problems.
try (var reader = …) { } closes resources automatically, even on errors.
Code example: Safe file reading and a custom exception#
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class InsufficientStockException extends RuntimeException {
InsufficientStockException(String product) { super("Not enough stock for " + product); }
}
public class Errors {
static void reserve(String product, int stock, int qty) {
if (qty > stock) throw new InsufficientStockException(product);
}
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("prices.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Could not read prices: " + e.getMessage());
}
try {
reserve("Laptop", 2, 5);
} catch (InsufficientStockException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Reservation check finished");
}
}
}
Could not read prices: prices.txt (No such file or directory) Not enough stock for Laptop Reservation check finished
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- try-with-resources closes the reader automatically.
- IOException (checked) is caught with a friendly message.
- A custom unchecked exception signals a business rule.
- finally always runs.
Real-world use case#
An order service throws InsufficientStockException, which the API layer turns into HTTP 409 Conflict.
Common mistakes#
Swallowing exceptions hides bugs. At least log them.
Catch specific types you can handle; let others propagate.
Best practices#
- Catch specific exceptions
- try-with-resources for files and connections
- Meaningful messages
- Log once, at the boundary
Remember this#
try → catch → finally.
Checked must be handled or declared.
try-with-resources closes automatically.
Practice exercise#
Your task: Parse "abc" with Integer.parseInt and print "Invalid number" instead of crashing.
Show solution
try {
int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Invalid number");
}
Mini quiz#
Which statement closes resources automatically?
Want more? Practise all Java MCQs · Java interview questions
My notes#
Saved in this browser.