Checked vs Unchecked Exceptions
What you'll learn: You'll understand when to use checked versus unchecked exceptions and how this choice shapes your API's usability and safety contract.
The Core Distinction
Programming languages that support exceptions often distinguish between checked exceptions (must be explicitly handled or declared) and unchecked exceptions (can propagate implicitly). This distinction fundamentally impacts how developers interact with your code.
Checked exceptions force callers to acknowledge potential failure scenarios at compile-time. Think of them as a contract: "This operation might fail in these specific, recoverable ways, and you must decide how to handle them." Examples include file-not-found or network-timeout errors.
Unchecked exceptions don't require explicit handling. They typically represent programming errors (null pointers, array bounds violations) or unexpected failures where recovery isn't realistic. The runtime allows them to bubble up without ceremony.
The Trade-offs
Checked exceptions provide safety through compiler enforcement. Developers can't accidentally ignore important error conditions. However, they increase API verbosity and can lead to "exception wrapping hell" where every layer must declare or handle exceptions from layers below.
Unchecked exceptions offer flexibility and cleaner code. They don't pollute method signatures and allow exceptions to traverse multiple layers naturally. The downside? Silent failures become possible—developers might not realize certain operations can fail.
API Design Impact
The choice signals intent to API consumers. Use checked exceptions for anticipated, recoverable conditions that callers should actively handle (authentication failures, validation errors). Use unchecked exceptions for programming mistakes or truly exceptional circumstances (out of memory, configuration errors).
Many modern languages (Python, JavaScript, C#) chose unchecked-only to avoid the verbosity debate entirely, relying instead on documentation and conventions.
Key Takeaway: Checked exceptions enforce safety through compile-time contracts but add verbosity; unchecked exceptions enable cleaner code but require discipline and documentation to avoid silent failures.