JAVA / CHAPTER 12
Exception handling
AdvancedHandle a specific failure without concealing unrelated errors.
By the end of this chapter
- Trace try/catch/finally
- Choose meaningful exception boundaries
- Preserve useful failure information
The idea
An exception interrupts ordinary statement execution and searches for a matching handler. Code after the failing statement in the same try block is skipped. A catch clause handles compatible exception types; order more specific handlers before general ones. Use exceptions for failures that the caller must distinguish, rather than turning every possible problem into a plausible-looking default result.
A finally block normally runs as control leaves the try/catch structure, making it useful for cleanup. For resources such as files, prefer try-with-resources when the resource implements AutoCloseable. Checked exceptions must be caught or declared where required; unchecked exceptions still deserve a deliberate policy. Catch near a boundary that can recover or explain the failure meaningfully.
public class Main {
public static void main(String[] args) {
try {
int count = Integer.parseInt("four");
System.out.println(count);
} catch (NumberFormatException ex) {
System.out.println("Invalid count");
} finally {
System.out.println("Finished");
}
}
}Invalid count Finished
Parsing fails before count can be printed. The matching handler explains the failure, and the finally block then runs.
Try it yourself
Parse a user-supplied integer and report a distinct validation error for malformed text.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING