Sobes.tech
Senior

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:

    1. Checked exceptions — inherit from Exception, but not from RuntimeException. The compiler requires these exceptions to be either caught in a try-catch block or declared in the method signature with throws. Examples: IOException, SQLException.

    2. Unchecked exceptions — inherit from RuntimeException. The compiler does not require mandatory handling or declaration of these exceptions. They usually arise from programming errors, such as NullPointerException, 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.

Tell me about the exception hierarchy in Java… - sobes.tech