Introduction to Exception Handling
What is an Exception?
An Exception is an unwanted or unexpected event that occurs during the execution of a program (at runtime), which disrupts the normal flow of instructions.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. This object, called an Exception Object, contains information about the error, including its type and the state of the program when the error occurred.
[!NOTE] The term Exception is shorthand for the phrase "exceptional event".
Why Do We Need Exception Handling?
The core advantage of exception handling is to maintain the normal flow of the application.
If a program doesn't handle an exception, the JVM abruptly terminates the program. However, by handling exceptions appropriately, we can:
- Prevent sudden program crashes.
- Provide meaningful error messages to users.
- Log error details for debugging.
- Perform clean-up operations (like closing files or database connections) before the program exits or continues.
Example Scenario
Imagine a program performing a sequence of instructions:
statement 1;
statement 2;
statement 3; // Exception occurs here
statement 4;
statement 5;
Without exception handling, if an exception occurs at statement 3, the program terminates immediately, and statements 4 and 5 will never execute. By implementing exception handling, statements 4 and 5 can execute normally even if statement 3 fails.
Error vs Exception
It is crucial to understand the difference between an Error and an Exception in Java.
| Feature | Error | Exception |
|---|---|---|
| Origin | Caused by the environment in which the application is running (e.g., JVM issues). | Caused by the application itself (e.g., bad user input, missing file). |
| Recoverability | Irrecoverable. The program usually cannot recover from an error. | Recoverable. The program can catch and handle exceptions. |
| Examples | OutOfMemoryError, StackOverflowError | NullPointerException, IOException, SQLException |
| Package | java.lang.Error | java.lang.Exception |
[!IMPORTANT] Both
ErrorandExceptionare subclasses of theThrowableclass, which is the root class of the Java exception hierarchy. We will explore this hierarchy in the next section.