πŸ“š

Understanding Exception Hierarchy in Java

May 1, 2025

Notes on Exception Hierarchy in Java

Overview

  • Exceptions are structured in a hierarchy.
  • Important to understand which exceptions need to be handled.

Class Hierarchy

  • Object Class:
    • Every class in Java extends from the Object class by default.
  • Throwable Class:
    • Two main subclasses: Exception and Error.

Key Concepts

  • Exceptions:
    • Something that can and should be handled.
  • Errors:
    • Issues that cannot be handled (e.g., OutOfMemoryError, I/O Error).

Exception Types

  • Runtime Exception:
    • Subclass of Exception.
    • Includes common exceptions:
      • ArithmeticException
      • IndexOutOfBoundsException
      • NullPointerException
    • Unchecked Exceptions:
      • Compiler does not force handling.
  • Checked Exceptions:
    • Must be handled by the programmer.
    • Example: SQL Exception, I/O Exception.

Compiler Behavior

  • Unchecked Exceptions:
    • No mandatory handling by the compiler.
  • Checked Exceptions:
    • Compiler requires the programmer to handle them.

Best Practices

  • Handle exceptions to maintain program stability and client satisfaction.
  • Even if handling a runtime exception is optional, it’s considered good practice to do so.