Lesson 33: Handling Errors: Introduction to Exceptions
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Java provides a robust mechanism to handle these errors.
The Exception Hierarchy
All exceptions and errors are subclasses of the Throwable class.
- Error: Represents serious problems (e.g.,
OutOfMemoryError,StackOverflowError). These are generally unrecoverable and should not be caught by the application. - Exception: Represents conditions that an application might want to catch and handle.
Checked vs. Unchecked Exceptions
Java exceptions are categorized into two types, based on whether the compiler forces you to handle them.
1. Checked Exceptions
- The compiler forces you to either handle them (using
try-catch) or declare them (usingthrows). - They typically represent external problems that are recoverable (e.g., file not found, network issues).
- Examples:
IOException,SQLException,FileNotFoundException.
2. Unchecked Exceptions (Runtime Exceptions)
- The compiler does not force handling.
- They usually result from programming errors or logic flaws (e.g., trying to access an invalid index).
- They are subclasses of
RuntimeException. - Examples:
NullPointerException,ArrayIndexOutOfBoundsException,ArithmeticException.
java // Example of an unchecked exception (programming error) int result = 10 / 0; // ArithmeticException
// Example of a checked exception (requires handling/declaration) // Thread.sleep(1000); // Compilation Error without try/catch or throws
Goal of Exception Handling: To gracefully manage unexpected situations, prevent application crashes, and provide meaningful feedback.