Sobes.tech
Junior — Middle

Explain the structure of the exception hierarchy in Java and its features

sobes.tech AI

Answer from AI

In Java, the exception hierarchy is based on the Throwable class, which has two main subclasses:

  • Error — errors related to the virtual machine (e.g., OutOfMemoryError), usually not handled in code.
  • Exception — exceptions that can and should be handled.

In turn, Exception is divided into:

  • Checked exceptions — require mandatory handling or declaration in the method signature (e.g., IOException).
  • Unchecked exceptions — descendants of RuntimeException (e.g., NullPointerException), do not require mandatory handling.

Features:

  • Checked exceptions force the programmer to explicitly handle errors, increasing reliability.
  • Unchecked exceptions usually signal programming errors.

Example:

try {
    // code that may throw IOException
} catch (IOException e) {
    e.printStackTrace();
}

Thus, the exception hierarchy helps structure error handling and differentiate between various problem types.