Exceptions
Java's exception mechanism separates the happy path from error-handling code, making intent clearer. The critical distinction — checked vs. unchecked exceptions — defines a contract between a method and its callers. Modern Java code leans toward unchecked exceptions, and
try-with-resources(Java 7+) eliminates entire categories of resource-leak bugs.
What You'll Find Here
| Topic | Description |
|---|---|
| Exception Hierarchy | Throwable → Error vs. Exception; checked vs. unchecked (RuntimeException). |
| try / catch / finally | Multi-catch |, finally guarantees, try-with-resources, suppressed exceptions. |
| Custom Exceptions | Creating domain-specific exceptions; typed fields; hierarchy design; Spring @ControllerAdvice integration. |
| Exception Best Practices | Fail-fast, never swallow, log-once, InterruptedException, and the checked vs. unchecked design decision. |
Learning Path
- Exception Hierarchy — understand the
Throwabletree; know thatErrorshould never be caught. - try / catch / finally — learn
try-with-resourcesfirst since it eliminates most explicitfinallyblocks. - Custom Exceptions — wrapping causes with the
(String, Throwable)constructor preserves the root cause; missing this is the #1 exception anti-pattern. - Exception Best Practices — the "never swallow" rule and the checked exception controversy are recurring interview topics.
Related Domains
- Core Java — control flow basics;
throwandthrowsare part of the language syntax. - Spring Boot —
@ExceptionHandlerand@ControllerAdvicebuild on custom exception design. - Testing —
assertThrowsin JUnit 5 requires understanding exception types.