In mission-critical enterprise systems, applications must handle unexpected runtime errors gracefully without abruptly crashing. Java provides a robust, object-oriented Exception Handling Framework rooted in the java.lang.Throwable class.
Figure 8: Complete Java Exception Hierarchy: Throwable branching into Error and Exception (Checked vs RuntimeException).
java.lang.ThrowableEvery exception in Java is an Object that directly or indirectly inherits from Throwable, which splits into two major branches:
Error (Fatal / System Failures)Errors indicate catastrophic internal JVM failures or system resource exhaustion that typical applications cannot anticipate or recover from. Never catch an Error! Examples include:
OutOfMemoryError: The JVM Heap has exhausted all available RAM.StackOverflowError: Infinite recursion has consumed the thread Call Stack.VirtualMachineError: Internal corruption within the JVM native engine.Exception (Recoverable Application Conditions)Exceptions represent conditions that a well-written application can catch, log, and recover from:
Exception (excluding RuntimeException). The compiler forces you to handle them (e.g. IOException, SQLException, FileNotFoundException).java.lang.RuntimeException. Caused by logical programming mistakes (e.g. NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException).| Parameter | Checked Exceptions | Unchecked (RuntimeException) |
|---|---|---|
| Compiler Check | Verified strictly at compile-time by javac |
Ignored at compile-time; occurs at runtime |
| Handling Requirement | Mandatory: Must use try-catch or throws |
Optional: Best practice is to fix the underlying code bug |
| Inherits From | Directly from java.lang.Exception |
Directly from java.lang.RuntimeException |
| Common Examples | IOException, ClassNotFoundException |
NullPointerException, ClassCastException |
Exam Question: "State the 5 keywords used for exception handling in Java."
The 5 Exception Keywords:
1. try: Wraps guarded code that might throw an exception.
2. catch: Catches and handles a specific exception type.
3. finally: Clean-up block guaranteed to execute regardless of errors.
4. throw: Explicitly triggers an exception instance.
5. throws: Declares potential checked exceptions in a method signature.
Now let us examine how to catch exceptions using Try, Catch, Finally, and Multi-Catch blocks. Proceed to: Java Try, Catch & Finally →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Handling exception blocks.
Throwing and declaring exceptions.
User-defined exception classes.
Automatic resource cleanup.