Choosing Between Checked and Unchecked
You'll learn: How to decide whether your exception should be checked or unchecked based on what went wrong and whether the caller can reasonably recover.
The Core Question
When designing your own exceptions or choosing which type to throw, you face a fundamental decision: should this be a checked exception (forcing callers to handle it) or an unchecked exception (allowing it to propagate automatically)?
The answer hinges on two questions:
- Can the caller do something meaningful about this problem? If yes → checked exception
- Is this a programming mistake that shouldn't happen? If yes → unchecked exception
Recoverable vs Programming Errors
Checked exceptions signal recoverable conditions—situations where the caller might take corrective action. Examples include file not found (try another path), network timeout (retry), or invalid user input (prompt again). These are external circumstances beyond the program's control.
Unchecked exceptions signal programming errors—bugs that shouldn't exist if the code were correct. Examples include null pointer dereferencing, array index out of bounds, or passing invalid arguments. These represent mistakes in your code logic.
The Decision Framework
Think of it like traffic signals:
- Checked = yellow light: "Caution ahead, prepare to stop or proceed carefully"
- Unchecked = red light violation alarm: "You've broken the rules, this shouldn't happen"
If you're validating external data or interacting with resources that might fail, use checked exceptions. If you're detecting violated contracts or preconditions that proper coding should prevent, use unchecked exceptions.
Key Takeaway: Use checked exceptions for conditions callers can recover from (external failures); use unchecked exceptions for programming bugs that proper code should prevent (internal failures).