Junior
What is the difference between checked and unchecked exceptions in Java?
sobes.tech AI
Answer from AI
The difference between checked and unchecked exceptions lies in how the compiler handles them and the requirement for explicit handling by the developer.
-
Checked Exceptions:
- Inherit from
Exception(but not fromRuntimeException). - The compiler checks that these exceptions are either handled (using
try-catch) or declared in the method signature (usingthrows). - Usually represent expected, recoverable errors (e.g., file input/output problems).
- Examples:
IOException,FileNotFoundException,SQLException.
- Inherit from
-
Unchecked Exceptions:
- Inherit from
RuntimeExceptionorError. - The compiler does not require explicit handling or declaration in the method signature.
- Usually represent programming errors or unrecoverable situations (e.g., array index out of bounds, null pointer).
- Examples:
NullPointerException,ArrayIndexOutOfBoundsException,IllegalArgumentException,ArithmeticException.
- Inherit from
The main difference is that for checked exceptions, the compiler requires either handling them or propagating them further, whereas for unchecked exceptions, this requirement does not exist, and they often indicate logic errors or runtime environment issues.
// Example of using a checked exception
import java.io.FileReader;
import java.io.IOException;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("nonexistentfile.txt"); // May throw FileNotFoundException (checked)
// Reading from the file
} catch (IOException e) { // Handling checked exception
System.err.println("File operation error: " + e.getMessage());
}
}
}
// Example of using an unchecked exception
public class UncheckedExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[5]); // May throw ArrayIndexOutOfBoundsException (unchecked)
} catch (ArrayIndexOutOfBoundsException e) { // Handling is optional but possible
System.err.println("Error: array index out of bounds");
}
String str = null;
// str.length(); // May throw NullPointerException (unchecked) - compiler does not require try-catch
}
}