Core Module
12 min forge
Java Exception Handling
Checked vs Unchecked exceptions, try-catch-finally, and custom exceptions.
Java Exception Handling
π What is it
Exception handling is a mechanism to handle runtime errors so that the normal flow of the application can be maintained. Java uses a robust hierarchy of Throwable classes.
ποΈ Hierarchy
- Throwable: Root class.
- Error: Irrecoverable conditions (e.g.,
OutOfMemoryError). - Exception: Recoverable conditions.
- Checked Exceptions: Checked at compile-time (e.g.,
IOException). - Unchecked Exceptions (Runtime): Checked at runtime (e.g.,
NullPointerException).
- Checked Exceptions: Checked at compile-time (e.g.,
- Error: Irrecoverable conditions (e.g.,
β‘ Keywords
try: Block where code that might throw an exception is placed.catch: Block that handles the exception.finally: Block that executes regardless of whether an exception was thrown (used for cleanup).throw: Used to explicitly throw an exception.throws: Declares that a method might throw an exception.
π» Code example
java Standardpublic class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.err.println("Cannot divide by zero!"); } finally { System.out.println("Cleanup successful."); } } }
β Common mistakes
- Catching Throwable: Catching
ThrowableorExceptionindiscriminately (swallowing errors). - Ignoring finally: Not using
finally(or try-with-resources) to close resources like file streams or database connections. - Checked vs Unchecked: Not understanding when to use checked exceptions (for recoverable conditions outside the app's control) vs unchecked (for programming errors).