Explain the differences between checked and unchecked exceptions in Java.
sobes.tech AI
Answer from AI
In Java, exceptions are divided into checked and unchecked.
-
Checked exceptions are exceptions that the compiler requires to be explicitly handled. They inherit from the
Exceptionclass but not fromRuntimeException. Examples:IOException,SQLException. When calling a method that might throw a checked exception, you must either handle it in atry-catchblock or declare it inthrows. -
Unchecked exceptions inherit from
RuntimeException. The compiler does not require them to be explicitly handled. Examples:NullPointerException,IllegalArgumentException. They usually occur due to programming errors and should not be explicitly handled.
Example:
try {
FileInputStream fis = new FileInputStream("file.txt"); // IOException - checked
} catch (IOException e) {
e.printStackTrace();
}
int a = 5 / 0; // ArithmeticException - unchecked
Thus, checked exceptions require explicit handling, while unchecked ones do not.