Exceptions

Exceptions

A school program needs reliable data and clear rules. An exception represents an abrupt failure in normal execution. A program can catch a specific problem and choose a recovery action instead of silently treating invalid data as correct.

  1. Understand

    An exception represents an abrupt failure in normal execution.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Catching an exception does not undo earlier changes. Recovery must restore any required state explicitly.

Exceptions

When you run a Java program, sometimes things go wrong. Maybe you're trying to divide a number by zero, or you're reading a file that doesn't exist. In Java, these "unexpected events" are called exceptions.

What is an Exception?

An exception is an event that disrupts the normal flow of a program. It’s a runtime error — something Java didn’t expect to happen while your code was running.

For example:

public class DivideByZero {
    public static void main(String[] args) {
        int result = 10 / 0;
        System.out.println("Result: " + result);
    }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero

Notice that Java didn’t just crash silently. It gave a detailed message — the type of error and the line where it happened. That’s part of what makes Java’s exception system so developer-friendly.

Types of Exceptions in Java

1. Checked Exceptions

These are exceptions that Java forces you to handle at compile time. They typically deal with external resources like files, databases, or network connections.

import java.io.File;
import java.io.FileReader;

public class CheckedExample {
    public static void main(String[] args) throws Exception {
        File file = new File("myfile.txt");
        FileReader reader = new FileReader(file); // May throw FileNotFoundException
    }
}

Java won't compile this code unless you either handle the exception with a try-catch block or declare it with throws.

2. Unchecked Exceptions

These are runtime exceptions, and Java does not require you to catch or declare them. Common examples include:

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
public class UncheckedExample {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.length()); // NullPointerException
    }
}
Exception in thread "main" java.lang.NullPointerException

Java Exception Hierarchy

All exceptions are part of the Throwable class. Here's a simplified view:

  • Throwable
    • Error – Serious problems (e.g., OutOfMemoryError)
    • Exception
      • Checked Exceptions – must be handled
      • Unchecked Exceptions – can be optionally handled

How to Handle Exceptions in Java

1. try-catch Block

This is the most common way to catch exceptions.

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Caught an exception: " + e.getMessage());
        }
    }
}
Caught an exception: / by zero

2. Multiple catch Blocks

Different exceptions can be caught separately.

public class MultiCatchExample {
    public static void main(String[] args) {
        try {
            int[] nums = {1, 2};
            System.out.println(nums[5]);
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index error");
        }
    }
}
Array index error

3. finally Block

This block always runs, whether or not there’s an exception. It's used for cleanup operations.

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int x = 5 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Handled exception.");
        } finally {
            System.out.println("Finally block always runs.");
        }
    }
}
Handled exception.
Finally block always runs.

Using throw to Manually Raise an Exception

public class ThrowExample {
    public static void main(String[] args) {
        throw new IllegalArgumentException("This is not allowed!");
    }
}
Exception in thread "main" java.lang.IllegalArgumentException: This is not allowed!

Using throws to Declare an Exception

If you want to let the caller handle an exception, you can declare it using throws.

import java.io.FileReader;

public class ThrowsExample {
    public static void main(String[] args) throws Exception {
        FileReader reader = new FileReader("nofile.txt");
    }
}
Exception in thread "main" java.io.FileNotFoundException: nofile.txt (No such file or directory)

Summary

  • Exceptions are Java’s way of telling you something went wrong.
  • Use try-catch to handle errors.
  • finally always runs, perfect for clean-up.
  • throw is used to raise exceptions manually.
  • throws passes the responsibility to the caller.

Important boundaries and mistakes

Catching an exception does not undo earlier changes. Recovery must restore any required state explicitly.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Catching an exception does not undo earlier changes.

Java 17 · Main.java · complete practice program

public class Main  {
  public static void main(String[] args)  {
    try  {
      Integer.parseInt("absent");
    }
    catch (NumberFormatException e)  {
      System.out.println("Enter a number");
    }
  }
}

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  public static void main(String[] args)  {
    try  {
      Integer.parseInt("absent");
    }
    catch (NumberFormatException e)  {
      System.out.println("Enter a number");
    }
  }
}

Expected output

Enter a number

An exception represents an abrupt failure in normal execution. A program can catch a specific problem and choose a recovery action instead of silently treating invalid data as correct.

Catching an exception does not undo earlier changes. Recovery must restore any required state explicitly.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

Enter a number

An exception represents an abrupt failure in normal execution. A program can catch a specific problem and choose a recovery action instead of silently treating invalid data as correct. Catching an exception does not undo earlier changes. Recovery must restore any required state explicitly.

What to remember

An exception represents an abrupt failure in normal execution. A program can catch a specific problem and choose a recovery action instead of silently treating invalid data as correct. Catching an exception does not undo earlier changes. Recovery must restore any required state explicitly.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Try Catch →