Junior — Middle
Can you list the types of exceptions used in Java and explain their differences?
sobes.tech AI
Answer from AI
In Java, exceptions are divided into two main categories:
-
Checked Exceptions
- Inherit from the class
Exception, but not fromRuntimeException. - The compiler requires these exceptions to be either caught in a
try-catchblock or declared in the method'sthrowsclause. - Used for situations that can be anticipated and handled, such as input-output errors (
IOException).
- Inherit from the class
-
Unchecked Exceptions
- Inherit from
RuntimeException. - The compiler does not require mandatory handling or declaration.
- Usually indicate programming errors, such as
NullPointerException,IllegalArgumentException.
- Inherit from
-
Errors
- Inherit from the class
Error. - Represent serious problems that are usually not handled by the application, such as
OutOfMemoryError.
- Inherit from the class
Differences:
- Checked exceptions require explicit handling, which helps in writing more reliable code.
- Unchecked exceptions are usually related to programming errors and do not require mandatory handling.
- Errors indicate problems at the JVM level and are generally not handled.
Example:
try {
FileReader file = new FileReader("file.txt"); // IOException - checked exception
} catch (IOException e) {
e.printStackTrace();
}
int a = 5 / 0; // ArithmeticException - unchecked exception