Module 9: Exceptions, Validation, and Debugging
Try, Catch, and Finally in Real Code
Handle failures clearly, catch the right exceptions, and keep cleanup code predictable.
Author
Java Learner Editorial Team
Reviewer
Technical review by Java Learner
Last reviewed
2026-04-17
Java version
Java 25 LTS
Learning goals
- Use `try/catch/finally` with clear intent
- Catch specific exceptions before generic ones
- Avoid swallowing failures silently
Catch what you can actually handle: If your catch block only prints a vague message and hides the failure, you made debugging harder.
Order matters: Catch specific exception types first, then broader ones later, or the specific ones become unreachable.
Use finally for cleanup when try-with-resources does not apply: It runs whether the try block succeeds or fails.
Intermediate habit: Include enough context in logs or messages so the next person understands what failed and where.
Runnable examples
Specific catch first, cleanup always
try {
int value = Integer.parseInt("42");
System.out.println(value);
} catch (NumberFormatException ex) {
System.out.println("Input was not a number.");
} finally {
System.out.println("Parsing attempt finished.");
}Expected output
42 Parsing attempt finished.
Common mistakes
Catching `Exception` immediately
Start with the specific exception types you understand and can handle usefully.
Leaving the catch block empty
Never swallow exceptions silently. Add context, rethrow, or handle the failure properly.
Mini exercise
Wrap an integer parse in a `try/catch` block and print a friendly message if the user enters text instead of a number.
Summary
- Catch specific exceptions where possible.
- `finally` is for guaranteed cleanup.
- A good catch block makes failures easier to understand, not harder.
Next step
Now let the language close resources for you with try-with-resources.
Sources used