What is an Exception in Java?

3 minute read

Every Java program encounters errors at some point — a file that doesn’t exist, a network connection that drops, a user who enters text instead of a number. Java’s exception handling mechanism gives you a structured way to detect, handle, and recover from these errors gracefully — instead of letting your program crash.

In this chapter, you’ll learn what exceptions are, how Java’s exception hierarchy is organized, and what happens when an exception is thrown.


What is an Exception?

An exception is an event that disrupts the normal flow of a program’s execution. When an error occurs inside a method, Java creates an exception object containing information about the error (type, message, stack trace) and “throws” it.

Think of it like a fire alarm:

  • Normal flow = everyone working in the building
  • Exception = fire alarm goes off
  • Exception handler = the evacuation plan

Without a handler, the program terminates. With a handler, the program can recover or fail gracefully.


The Throwable Hierarchy

All exceptions and errors in Java inherit from the Throwable class:

                    Throwable
                   /         \
               Error         Exception
              /     \             \
   OutOfMemoryError  StackOverflowError   RuntimeException      IOException
                                         /        \                  \
                          NullPointerException  ArrayIndexOutOf...  FileNotFoundException

Three categories:

Category Examples Should You Catch?
Error OutOfMemoryError, StackOverflowError ❌ No — JVM-level problems you can’t fix
Checked Exception IOException, SQLException ✅ Yes — compiler forces you to handle them
Unchecked Exception (RuntimeException) NullPointerException, ArrayIndexOutOfBoundsException ⚠️ Optional — usually indicates programming bugs

What Happens When an Exception is Thrown?

When code throws an exception, Java performs stack unwinding — it walks back up the call stack looking for a matching catch block:

public class ExceptionDemo {
    public static void main(String[] args) {
        System.out.println("Start");
        methodA();
        System.out.println("End"); // This line is SKIPPED if exception is uncaught
    }

    static void methodA() {
        methodB();
    }

    static void methodB() {
        int result = 10 / 0; // 💥 ArithmeticException
    }
}

Output:

Start
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at ExceptionDemo.methodB(ExceptionDemo.java:13)
    at ExceptionDemo.methodA(ExceptionDemo.java:9)
    at ExceptionDemo.main(ExceptionDemo.java:4)

The stack trace shows the exact chain of method calls that led to the error — read it bottom to top to trace the execution path.


Checked vs Unchecked Exceptions — Quick Preview

  Checked Unchecked
Superclass Exception (but not RuntimeException) RuntimeException
Compiler enforced? ✅ Yes — must handle or declare ❌ No
Examples IOException, SQLException NullPointerException, IllegalArgumentException
Typical cause External factors (file, network, DB) Programming bugs

We’ll explore this in detail in Chapter 44: Checked vs Unchecked Exceptions.


Your First Exception Example

public class DivisionExample {
    public static void main(String[] args) {
        int numerator = 10;
        int denominator = 0;

        try {
            int result = numerator / denominator;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
            System.out.println("Exception message: " + e.getMessage());
        }

        System.out.println("Program continues normally.");
    }
}

Output:

Error: Cannot divide by zero!
Exception message: / by zero
Program continues normally.

Notice that the program continues after the catch block — the exception was handled, so it didn’t crash.


Common Mistakes

Mistake Why It’s Wrong
Ignoring exceptions (empty catch block) Hides bugs — you’ll never know something went wrong
Catching Exception broadly Too generic — catches exceptions you didn’t intend to handle
Not reading the stack trace The stack trace tells you exactly where and why the error occurred

Try It Yourself

  1. Write a program that tries to access arr[10] on an array of size 5 — observe the exception
  2. Write a program that tries to convert "hello" to an integer with Integer.parseInt() — observe the exception
  3. Add a try-catch block to handle both cases gracefully

What’s Next?

In the next chapter, you’ll learn the full try-catch-finally syntax and how to handle exceptions properly in Java.

Updated: