Exceptions, Try-Catch-Finally & Try-With-Resources
Handle runtime failures gracefully using try-catch, multi-catch, try-with-resources (AutoCloseable), custom exceptions, and best practices.
- `Error`: Severe JVM/system failures (
OutOfMemoryError,StackOverflowError,NoClassDefFoundError). Applications generally cannot recover from these and should not catch them. - `Exception`:
Checked Exceptions (`IOException`, `SQLException`, `ClassNotFoundException`): Verified at compile time; the caller must* either handle them with
try-catchor declarethrowsin the method signature.
Introduction
In production software, failures are inevitable: network timeouts, missing files, invalid user input, and database deadlocks. Java's exception handling architecture separates normal business logic from error recovery, ensuring resources are never leaked and failures propagate with rich diagnostic stack traces.
Exception Hierarchy
Every throwable object inherits from java.lang.Throwable, which splits into two distinct branches:
- `Error`: Severe JVM/system failures (
OutOfMemoryError,StackOverflowError,NoClassDefFoundError). Applications generally cannot recover from these and should not catch them. - `Exception`:
- Checked Exceptions (
IOException,SQLException,ClassNotFoundException): Verified at compile time; the caller must either handle them withtry-catchor declarethrowsin the method signature. - Unchecked Exceptions (
RuntimeExceptionsubclasses such asNullPointerException,IllegalArgumentException,ArithmeticException,IndexOutOfBoundsException): Not checked at compile time; usually indicate programming bugs or violated preconditions.
How Exception Propagation & Call Stack Unwinding Work
When an exception is thrown inside a method, the JVM halts normal execution and searches the current method's exception table for a matching catch block. If none exists, the JVM pops the current stack frame and repeats the search in the caller method (exception propagation) until a handler is found or the thread terminates.
Try-With-Resources (Java 7+)
Before Java 7, closing files or database connections required verbose finally blocks that could mask the original exception if close() itself threw an error. Try-with-resources (try (var res = ...) { ... }) automatically closes any AutoCloseable resource in reverse declaration order and preserves suppressed exceptions cleanly via getSuppressed().
final vs finally vs finalize
| Keyword / Method | Role |
|---|---|
final | Prevents variable reassignment, method overriding, or class inheritance |
finally | Block that always executes after try/catch (unless System.exit() or JVM crash) |
finalize() | Deprecated GC cleanup hook; never rely on it—use AutoCloseable instead |
Common Mistakes & Best Practices
- Never write empty
catch (Exception e) {}blocks that silently hide bugs. - Always catch most-specific exceptions before broader ones (e.g.,
FileNotFoundExceptionbeforeIOException). - Never use exceptions for normal control flow (like exiting a loop)—stack trace capture is expensive.
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)