Exception handling
Exception handling and assertions are essential features in Java that help developers write robust and error-resilient code. While exception handling is used to manage runtime errors gracefully, assertions are used to test assumptions during development. Together, they contribute to building reliable and maintainable applications.
Exception Handling in Java
What is an Exception?
An exception is an event that disrupts the normal flow of a program during runtime. It occurs due to various reasons, such as invalid user input, file not found, network issues, or arithmetic errors (e.g., division by zero). Java provides a robust mechanism to handle such exceptions and prevent the program from crashing.
Exception Hierarchy
In Java, all exceptions are derived from the Throwable class. The hierarchy is as follows:
Throwable
- Error: Represents serious issues that applications should not handle (e.g.,
OutOfMemoryError). - Exception: Represents conditions that applications might want to catch and handle.
- Checked Exceptions: Exceptions that must be handled at compile time (e.g.,
IOException,SQLException). - Unchecked Exceptions: Exceptions that occur at runtime and do not require mandatory handling (e.g.,
NullPointerException,ArithmeticException).
- Checked Exceptions: Exceptions that must be handled at compile time (e.g.,
_1743004272899.png)
Checked vs Unchecked Exceptions in Java
Checked Exceptions:
Checked exceptions are exceptions that are checked at compile time. The Java compiler ensures that these exceptions are either handled using a try-catch block or declared in the method signature using the throws keyword. If not handled, the code will fail to compile.
Examples:
IOExceptionSQLExceptionFileNotFoundExceptionClassNotFoundException
Characteristics:
- Must be handled explicitly in the code.
- Represent conditions that a program should anticipate and recover from (e.g., file not found, database connection failure).
- Typically used for external resources like files, databases, or network operations.
Example of Checked Exception:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("nonexistent.txt");
FileReader reader = new FileReader(file); // May throw FileNotFoundException
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
In this example, the
FileReaderconstructor throws aFileNotFoundException, which is a checked exception. The code must handle it using atry-catchblock.
Unchecked Exceptions
Unchecked exceptions are exceptions that are not checked at compile time. These exceptions occur during runtime and are typically caused by programming errors, such as invalid logic or improper use of APIs.
Examples:
NullPointerExceptionArithmeticExceptionArrayIndexOutOfBoundsExceptionIllegalArgumentException
Characteristics:
- Do not need to be explicitly handled or declared in the method signature.
- Represent programming errors or bugs that the program cannot recover from (e.g., accessing a null object, dividing by zero).
- Typically extend the
RuntimeExceptionclass.
Example of Unchecked Exception:
public class UncheckedExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Throws ArrayIndexOutOfBoundsException
}
}
In this example, accessing an invalid array index throws an ArrayIndexOutOfBoundsException, which is an unchecked exception. The program will terminate unless the exception is handled.
In this example, accessing an invalid array index throws an ArrayIndexOutOfBoundsException, which is an unchecked exception. The program will terminate unless the exception is handled.
Comparison
Aspect | Checked Exceptions | Unchecked Exceptions |
|---|---|---|
Compile-Time Check | Checked at compile time. | Not checked at compile time. |
Handling Requirement | Must be handled using try-catch or declared with throws. | Handling is optional. |
Cause | Represent recoverable conditions (e.g., file not found). | Represent programming errors (e.g., null pointer). |
Class Hierarchy | Subclasses of Exception (excluding RuntimeException). | Subclasses of RuntimeException. |
Examples | IOException, SQLException, FileNotFoundException. | NullPointerException, ArithmeticException. |
