Stop 07 · Exception Handling & File I/OTopics · 1/8

Checked vs Unchecked Exceptions

Part of the Java Roadmap

In short

Some failures are nobody's fault, like a missing file or a dropped network. Others are plain bugs. Java splits exceptions into these two families, and the compiler treats them very differently.

Checked exceptions (like IOException) must be caught or declared, while unchecked exceptions (subclasses of RuntimeException, like NullPointerException) usually signal programming bugs.

The jaadu holds an open umbrella against heavy monsoon rain with one hand while frowning at a bicycle with a flat tyre lying beside it.

Think of it like this

Rain vs a broken bicycle

Before leaving for college in Mumbai during the monsoon, your mother insists you carry an umbrella. Rain is expected and outside your control, so you must plan for it. That is a checked exception. A flat tyre because you never pumped it is your own mistake. Nobody makes you carry a repair kit for that; you just fix the habit. That is an unchecked exception.

Watch it happen

The Throwable family tree

Throwable
Error
OutOfMemoryError
Exception
IOException
RuntimeException
NullPointerException
IllegalArgumentException

1/4Everything you can throw extends Throwable.

The big ideas

What you need to know

Checked = catch or declare

For checked exceptions the compiler refuses to compile until you either catch them or add throws to the method signature.

Unchecked = usually a bug

NullPointerException, ArrayIndexOutOfBoundsException and IllegalArgumentException come from mistakes in code. Fix the cause instead of wrapping everything in try.

Errors are different again

OutOfMemoryError and StackOverflowError are Errors, not Exceptions. Your program usually cannot recover from them.

How to choose

If a careful caller could still hit the problem (file missing, server down), checked fits. If only a careless caller hits it (negative quantity), use unchecked.

See it in code

Walk through the code

java
1import java.io.IOException;2import java.nio.file.Files;3import java.nio.file.Path;4 5public class FeeReport {6 7    // Checked: the compiler forces callers to deal with IOException8    static String readFees(Path file) throws IOException {9        return Files.readString(file);10    }11 12    // Unchecked: a bad argument is the caller's bug, no throws needed13    static int perStudent(int totalFees, int students) {14        if (students <= 0) {15            throw new IllegalArgumentException("students must be positive");16        }17        return totalFees / students;18    }19 20    public static void main(String[] args) {21        try {22            System.out.println(readFees(Path.of("fees.txt")));23        } catch (IOException e) {24            System.out.println("Could not read fees file: " + e.getMessage());25        }26        System.out.println(perStudent(120000, 40));27    }28}

1/4Files.readString can throw IOException, a checked exception, so the method must say throws IOException.

One checked and one unchecked exception side by side. Remove the try/catch around readFees and the code stops compiling. Remove nothing around perStudent and it still compiles.

Save yourself the pain

Common mistakes

Oops

Catching NullPointerException to hide it: try { name.length(); } catch (NullPointerException e) {}

Do this instead

Check for null or make sure the value is set. Unchecked exceptions are signals to fix the code, not to silence it.

Oops

Thinking unchecked means 'cannot be caught'.

Do this instead

You can catch any exception. Unchecked only means the compiler does not force you to.

Oops

Catching Throwable or Error in normal application code.

Do this instead

Catch the most specific Exception type you can actually handle. Errors like OutOfMemoryError should usually be left alone.

Your mission

Sort the exceptions

~15 min

Quick check

Which of these is a checked exception?

Go deeper

  1. 1Draw the hierarchy: Throwable, Error, Exception and RuntimeException.
  2. 2Trigger three common unchecked exceptions and read their stack traces.
  3. 3Learn why the compiler forces you to handle checked exceptions.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge