In Java, exceptions are classified into two major categories: Checked exceptions and Unchecked exceptions. These categories help differentiate how exceptions are handled and when they are raised.
Types of Exceptions in Java
1. Checked Exceptions
These are exceptions that must be explicitly handled by the programmer. They are checked by the compiler at compile-time, and the program will not compile unless these exceptions are properly caught or declared.
Examples:
IOException
— Thrown when an input/output operation fails (e.g., reading a file).SQLException
— Thrown when there’s a database access error.FileNotFoundException
— Thrown when a file is not found.ClassNotFoundException
— Thrown when the JVM cannot find a class at runtime.
Characteristics:
- Must be handled using
try-catch
blocks or declared usingthrows
. - A programmer must explicitly handle these exceptions to avoid compile-time errors.
2. Unchecked Exceptions
These exceptions are not checked at compile-time. The compiler does not force you to handle them. They are usually caused by programming bugs, such as logic errors or improper use of APIs.
Examples:
NullPointerException
— Thrown when a null reference is used.ArithmeticException
— Thrown for invalid arithmetic operations (e.g., division by zero).ArrayIndexOutOfBoundsException
— Thrown when an invalid array index is accessed.ClassCastException
— Thrown when an invalid cast between object types occurs.IllegalArgumentException
— Thrown when an illegal argument is passed to a method.
Characteristics:
- These exceptions are not mandatory to handle.
- They typically occur due to programming mistakes that need to be fixed.
3. Errors
Errors are not exceptions but rather represent serious problems that typically cannot be recovered from. These are not meant to be handled by programs.
Examples:
OutOfMemoryError
— Thrown when the JVM runs out of memory.StackOverflowError
— Thrown when a stack overflow occurs (e.g., due to excessive recursion).VirtualMachineError
— Thrown when the JVM is unable to execute a program properly.
Characteristics:
- Errors are not handled in typical exception handling.
- These indicate serious issues with the system or the JVM itself.
Type of Exception | Example | Handling Requirement |
---|---|---|
Checked Exceptions | IOException , SQLException |
Must be handled or declared using throws |
Unchecked Exceptions | NullPointerException , ArithmeticException |
Not required to be handled |
Errors | OutOfMemoryError , StackOverflowError |
Not typically handled |