Unchecked exceptions

In Java, unchecked exceptions are exceptions that do not require explicit handling by the programmer (i.e., they are not checked at compile time). These exceptions are subclasses of the RuntimeException class and represent errors that are typically the result of programming bugs or logic errors.

Here’s a breakdown of the unchecked exceptions hierarchy:


1. Throwable Class

  • The root of all error and exception classes in Java.

    • Throwable has two main subclasses:

      • Error: Represents serious issues that usually cannot be recovered from (e.g., OutOfMemoryError).

      • Exception: Represents all exceptions, including checked and unchecked exceptions.


2. RuntimeException Class (The Base Class for Unchecked Exceptions)

  • All unchecked exceptions inherit from RuntimeException. These exceptions occur due to errors in the program’s logic, and they are not mandatory to handle.

  • Common subclasses:
      • NullPointerException — Occurs when trying to access or modify an object reference that is null.

      • ArrayIndexOutOfBoundsException — Thrown when trying to access an array element using an invalid index.

      • ArithmeticException — Thrown when an arithmetic operation fails (e.g., division by zero).

      • ClassCastException — Thrown when trying to cast an object to an incompatible class.

      • IllegalArgumentException — Thrown when a method receives an invalid argument.

      • NumberFormatException — Thrown when trying to convert a string to a number, but the string doesn’t represent a valid number.


3. Common Subclasses of RuntimeException

  • NullPointerException: Occurs when a method attempts to access an object or variable that is null.

  • ArrayIndexOutOfBoundsException: Occurs when an invalid index is accessed in an array.

  • ArithmeticException: Typically occurs for arithmetic errors such as division by zero.

  • ClassCastException: Raised when an invalid cast occurs, such as trying to cast a subclass object to a superclass object.

  • IllegalArgumentException: Thrown when a method receives an argument that it doesn’t know how to handle.

  • NumberFormatException: Happens when trying to convert a non-numeric string to a number.

  • IllegalStateException: Indicates that a method has been invoked at an illegal or inappropriate time.

  • IndexOutOfBoundsException: Thrown when an index is out of range for a collection or array.

  • UnsupportedOperationException: Indicates that the requested operation is not supported.

Unchecked exceptions in Java are typically caused by logical errors in the program (such as invalid method arguments or attempting operations on null values). Since these exceptions are the result of programming mistakes, Java does not require them to be explicitly handled or declared. However, it is still important for developers to anticipate and fix these errors to ensure the program operates smoothly.

Scroll to Top