Skip to lesson

Checked and unchecked exceptions

Reading a file forces you to handle a possible error, but dividing by zero does not. Why does Java treat some errors so differently?

The handle-or-declare rule

A checked exception is one the compiler forces you to catch or declare with throws, such as IOException; unchecked exceptions are RuntimeException and its subclasses.

The handle-or-declare rule says: if a statement can throw a checked exception, its method must either catch it (handle) or list it after throws (declare). The compiler checks this before the program ever runs.

Example 1 · Handle it or declare it

HandleOrDeclareDemo.javaJava
import java.io.IOException;
public class HandleOrDeclareDemo {    // stands in for reading a marks file from disk    static int readMarks(String roll) throws IOException {        if (roll.isEmpty()) {            throw new IOException("no roll number given");        }        return 70 + roll.length();    }
    // Choice 1: handle it here with try-catch    static void printMarks(String roll) {        try {            System.out.println(roll + ": " + readMarks(roll));        } catch (IOException e) {            System.out.println("Could not read marks: " + e.getMessage());        }    }
    // Choice 2: declare it and let the caller decide    static int totalOfTwo(String a, String b) throws IOException {        return readMarks(a) + readMarks(b);    }
    public static void main(String[] args) {        printMarks("CS101");        printMarks("");        try {            System.out.println("Total: " + totalOfTwo("CS101", "CS2"));            System.out.println("Total: " + totalOfTwo("CS101", ""));        } catch (IOException e) {            System.out.println("main caught: " + e.getMessage());        }    }}
Output
CS101: 75
Could not read marks: no roll number given
Total: 148
main caught: no roll number given

What this code does

  • printMarks handles the exception itself, so its header has no throws, and its callers do not need a try.
  • totalOfTwo declares throws IOException and has no try. The exception from readMarks("") passes through it to main, which must handle it.

Handling means a try-catch around the call, with a useful answer in the catch: a message, a default value, a second try. Declaring means "I cannot deal with this here; my caller must". The exception then moves up to the method that called this one, and the same rule applies there. The point of the rule is that problems outside your control, such as a missing file or a dropped network, cannot be forgotten. The compiler will not let a program ignore them by accident.

The throws clause

A throws clause is the part of a method header that lists the checked exceptions the method may pass to its caller: static String load(String day) throws IOException. Several types are separated by commas.

Example 2 · throws with two types, and a parent covering a child

ThrowsChainDemo.javaJava
import java.io.FileNotFoundException;import java.io.IOException;
public class ThrowsChainDemo {    static String openTimetable(String day) throws FileNotFoundException {        if (day.equals("Sunday")) {            throw new FileNotFoundException("timetable-" + day + ".txt");        }        return "Timetable for " + day;    }
    // IOException also covers FileNotFoundException, its child    static String loadTimetable(String day) throws IOException, InterruptedException {        if (day.isBlank()) {            throw new InterruptedException("loading stopped");        }        return openTimetable(day);    }
    public static void main(String[] args) {        String[] days = {"Monday", "Sunday", " "};        for (String day : days) {            try {                System.out.println(loadTimetable(day));            } catch (IOException e) {                System.out.println("File problem: " + e.getMessage());            } catch (InterruptedException e) {                System.out.println("Stopped: " + e.getMessage());            }        }    }}
Output
Timetable for Monday
File problem: timetable-Sunday.txt
Stopped: loading stopped

What this code does

  • loadTimetable calls openTimetable, which may throw FileNotFoundException. Declaring the parent IOException is enough to satisfy the rule.
  • Two checked types are declared, separated by a comma, so main handles both: one catch for each.

Do not mix it up with throw. throw is a statement that throws one exception object right now. throws is a label on the method that warns callers what may come out of it. Declaring a parent class covers all its children. A method with throws IOException may pass on a FileNotFoundException, because that class is below IOException in the tree.

For a quick test program, public static void main(String[] args) throws IOException compiles. If the exception does happen, the JVM prints the stack trace and the program stops.

RuntimeException and its subclasses are unchecked

An unchecked exception is a RuntimeException, any of its subclasses, or an Error. The compiler does not ask you to catch or declare them, so a method can throw IllegalArgumentException without a throws clause.

Example 3 · An unchecked exception needs no throws

UncheckedDemo.javaJava
public class UncheckedDemo {    static int berthsLeft(int total, int booked) {        if (booked > total) {            throw new IllegalArgumentException("booked " + booked + " is more than " + total);        }        return total - booked;    }
    public static void main(String[] args) {        System.out.println("Berths left: " + berthsLeft(72, 60));   // compiles with no try
        try {            System.out.println("Berths left: " + berthsLeft(72, 80));        } catch (IllegalArgumentException e) {            System.out.println("Booking error: " + e.getMessage());        }    }}
Output
Berths left: 12
Booking error: booked 80 is more than 72

What this code does

  • berthsLeft throws IllegalArgumentException with no throws clause. It is a RuntimeException, so the compiler does not check it.
  • The first call has no try and still compiles. The second call is wrapped only because this program wants a friendly message, not because the compiler asked.

The reason is practical. Almost any line could throw one: every . on an object could be a NullPointerException, every / an ArithmeticException. If all of them had to be declared, every method would need a long throws list. And they mostly mean a bug, which is fixed by changing the code, not by catching. You may still catch an unchecked exception when you have a real answer for it, such as bad text typed by a user. Listing one in throws is allowed too, but only as documentation.

Compiler error: unreported exception

unreported exception X; must be caught or declared to be thrown is the compiler's message when the handle-or-declare rule is broken. It points at the exact line, and names the checked exception that is not dealt with.

Example 4 · Two unreported exceptions

UnreportedDemo.javaJava
import java.io.IOException;
public class UnreportedDemo {    static int readFee(String roll) {        if (roll.isEmpty()) {            throw new IOException("fee file missing");        }        return 45000;    }
    public static void main(String[] args) {        System.out.println("Checking fee...");        Thread.sleep(500);        System.out.println(readFee("CS101"));    }}
Sample compiler output
UnreportedDemo.java:6: error: unreported exception IOException; must be caught or declared to be thrown
            throw new IOException("fee file missing");
            ^
UnreportedDemo.java:13: error: unreported exception InterruptedException; must be caught or declared to be thrown
        Thread.sleep(500);
                    ^
2 errors

What this code does

  • Line 6 throws a checked IOException in a method with no throws. Line 13 calls Thread.sleep, which declares throws InterruptedException, without a try.
  • Fix readFee with throws IOException, and the error moves to main, the caller. Then fix main with a try-catch for both types, or with throws IOException, InterruptedException.
  • The exception can come from your own throw new IOException(...) or from a library method that declares it, such as Thread.sleep, which throws InterruptedException.
  • Fix 1: wrap the call in try-catch when this method can do something useful about the problem.
  • Fix 2: add throws X to the method header when only the caller knows what to do. The caller then gets the same rule.
  • The opposite mistake also fails: catching a checked exception that the try block can never throw gives exception X is never thrown in body of corresponding try statement.

Fix the error

Fix the unreported exception

Read the error, then pick the line that fixes it.

Round 1 of 2

save() declares a checked exception. Pick the line that makes main compile.

import java.io.IOException;
public class Report {
static void save() throws IOException {
throw new IOException("disk full");
}
public static void main(String[] args) {
save();
}
}

Error

Report.java:7: error: unreported exception IOException; must be caught or declared to be thrown
        save();
            ^

Next step

Check your understanding

12 quick questions