Web Analytics

Java Exceptions

Intermediate ~15 min read

An Exception is an event (problem) that occurs during the execution of a program that disrupts the normal flow of instructions. Java provides a powerful mechanism to handle these runtime errors so that the normal flow of the application can be maintained.

The Hierarchy

All exception types are subclasses of the class Throwable.

Java Exception Hierarchy Diagram
  • Error: Serious problems that a reasonable application should not try to catch (e.g., OutOfMemoryError).
  • Exception: Conditions that a reasonable application might want to catch.

Types of Exceptions

There are mainly two types of exceptions:

1. Checked Exceptions

Exceptions that are checked at compile-time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

  • Examples: IOException, SQLException.

2. Unchecked Exceptions (Runtime Exceptions)

Exceptions that are not checked at compile-time. They usually occur due to programming errors.

  • Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.

Summary

Remember: Errors are usually fatal (system crashes). Exceptions are manageable issues that your code can recover from.