Tell me about the exception hierarchy in Java, checked and unchecked exceptions
sobes.tech AI
Answer from AI
In Java, the exception hierarchy starts with the class java.lang.Throwable, which has two main subclasses: Error and Exception.
-
Error — errors that are usually not handled by the application (e.g.,
OutOfMemoryError). They indicate serious problems in the JVM. -
Exception — exceptions that can be handled by the program. Exceptions are divided into:
-
Checked exceptions — inherit from
Exception, but not fromRuntimeException. The compiler requires these exceptions to be either caught in atry-catchblock or declared in the method signature withthrows. Examples:IOException,SQLException. -
Unchecked exceptions — inherit from
RuntimeException. The compiler does not require mandatory handling or declaration of these exceptions. They usually arise from programming errors, such asNullPointerException,IllegalArgumentException.
-
Example:
try {
// code that may throw IOException
} catch (IOException e) {
e.printStackTrace();
}
// Unchecked exception can be not handled
int a = 5 / 0; // ArithmeticException
Thus, checked exceptions are intended for situations that can and should be handled, while unchecked exceptions are for errors that usually indicate bugs in the code.