Skip to lesson

Exceptions: Checked vs Unchecked, finally, throw vs throws

"Checked vs unchecked?" and "does finally always run?" appear in almost every Java round. The interviewer wants the hierarchy, the exact rules for throw, throws and finally, and clean handling instead of catching everything.

Recap: the Throwable hierarchy, Error vs Exception

Throwable is the root class of everything that can be thrown in Java. It has two branches: Error, for serious JVM problems you normally do not catch, and Exception, for conditions a program can handle.

The exception family has one root. This program prints which branch some common exceptions belong to.

Throwable is at the top, with two groups under it. Error: serious problems such as StackOverflowError and OutOfMemoryError. Exception: checked exceptions such as FileNotFoundException. Under Exception is RuntimeException: unchecked exceptions such as ArithmeticException and NullPointerException.

Example 1 · The hierarchy to draw

Text
                     Throwable                    /         \               Error           Exception        (do not catch)        /          \   OutOfMemoryError    IOException     RuntimeException  (unchecked)   StackOverflowError  SQLException     NullPointerException                       (checked)        ArithmeticException                                        IllegalArgumentException                                          NumberFormatException                                        IndexOutOfBoundsException
Rule
Checked = Exception minus RuntimeException. Unchecked = RuntimeException family (and Errors).

What this code does

  • If a class is under RuntimeException, the compiler does not force you to handle it; anywhere else under Exception, it does.
  • NumberFormatException sits under IllegalArgumentException: a common follow-up question, and the reason they cannot share one multi-catch.

Under Exception, RuntimeException and its subclasses are unchecked. Error examples: OutOfMemoryError, StackOverflowError; do not catch them to "fix" anything. Checked: Exception but not RuntimeException (IOException, SQLException). Unchecked: NullPointerException, ArithmeticException, NumberFormatException.

Revise: The exception family tree (opens in a new tab).

Checked vs unchecked; throw vs throws

A checked exception is an exception the compiler forces you to handle: the code must catch it or declare it with throws. IOException and SQLException are checked. Unchecked exceptions need neither.

throw throws one exception object; throws is the warning on a method signature. This program uses both, with a checked and an unchecked exception.

Example 2 · throws declares, throw throws

CheckedVsUnchecked.javaJava
class InvalidFeeException extends Exception {    InvalidFeeException(String message, Throwable cause) {        super(message, cause);    }}
public class CheckedVsUnchecked {    static int parseFee(String text) throws InvalidFeeException {        int fee;        try {            fee = Integer.parseInt(text);                               // may throw unchecked NumberFormatException        } catch (NumberFormatException e) {            throw new InvalidFeeException("Not a number: " + text, e);  // throws, keeping the cause        }        if (fee < 0) {            throw new InvalidFeeException("Negative fee: " + fee, null);        }        return fee;    }
    public static void main(String[] args) {        for (String t : new String[] {"45000", "abc", "-10"}) {            try {                System.out.println("Fee: " + parseFee(t));            } catch (InvalidFeeException e) {                System.out.println("Rejected: " + e.getMessage()                        + (e.getCause() != null ? " (cause: " + e.getCause().getClass().getSimpleName() + ")" : ""));            }        }        int[] seats = new int[2];        try {            seats[5] = 1;                                               // no throws needed: unchecked        } catch (ArrayIndexOutOfBoundsException e) {            System.out.println("Unchecked: " + e.getClass().getSimpleName());        }    }}
Output
Fee: 45000
Rejected: Not a number: abc (cause: NumberFormatException)
Rejected: Negative fee: -10
Unchecked: ArrayIndexOutOfBoundsException

What this code does

  • InvalidFeeException extends Exception, so it is checked: parseFee must declare it with throws, and main must catch it, or the code does not compile.
  • The unchecked NumberFormatException is wrapped as the cause, so no detail is lost. The array error is unchecked, so no throws was needed anywhere.

new FileReader("a.txt") alone fails with unreported exception FileNotFoundException; must be caught or declared to be thrown. An unchecked exception usually signals a bug, so it needs neither. throw new InvalidFeeException("Negative fee") acts; int parseFee(String s) throws InvalidFeeException declares.

Revise: Checked vs unchecked exceptions (opens in a new tab) and throw and throws (opens in a new tab).

Fix the error

Fix the unreported exception

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

Round 1 of 2

Open a file of fees.

import java.io.FileReader;
public class ReadFee {
public static void main(String[] args) {
FileReader reader = new FileReader("fees.txt");
System.out.println("opened");
}
}

Error

ReadFee.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        FileReader reader = new FileReader("fees.txt");
                            ^

finally: when it runs and when it does not

A finally block runs after try and any matching catch, whether the code finished normally, returned or threw an exception. It is used for clean-up and does not run if the JVM stops first.

This program shows finally with a return, then try-with-resources closing in reverse order. Another small program shows when finally does not run.

Three paths: no exception (the rest of try runs), an exception that is caught (the catch block runs) and an exception that is not caught (no catch runs). All three go through finally. Then the code after it runs, or, when nothing caught the exception, the program stops.

Example 3 · finally with return, and try-with-resources order

FinallyDemo.javaJava
class Resource implements AutoCloseable {    private final String name;
    Resource(String name) {        this.name = name;        System.out.println("open " + name);    }
    @Override    public void close() {        System.out.println("close " + name);    }}
public class FinallyDemo {    static int tryReturn() {        try {            return 1;        } finally {            System.out.println("finally runs before the return completes");        }    }
    @SuppressWarnings("finally")    static int finallyOverrides() {        try {            return 1;        } finally {            return 2;                 // bad practice: replaces the try's value        }    }
    public static void main(String[] args) {        System.out.println("returned " + tryReturn());        System.out.println("finally return wins: " + finallyOverrides());
        try (Resource db = new Resource("db"); Resource file = new Resource("file")) {            System.out.println("using both");            throw new IllegalStateException("boom");        } catch (IllegalStateException e) {            System.out.println("caught " + e.getMessage());        } finally {            System.out.println("outer finally");        }    }}
Output
finally runs before the return completes
returned 1
finally return wins: 2
open db
open file
using both
close file
close db
caught boom
outer finally

What this code does

  • tryReturn shows that finally runs even when try returns; finallyOverrides shows why a return in finally is dangerous.
  • The resources close in reverse order (file, then db) before the catch runs, and finally comes last.

Example 4 · When finally does not run

ExitSkipsFinally.javaJava
public class ExitSkipsFinally {    public static void main(String[] args) {        try {            System.out.println("in try, calling System.exit(0)");            System.exit(0);        } finally {            System.out.println("finally");      // never printed        }    }}
Output
in try, calling System.exit(0)

What this code does

  • System.exit(0) stops the JVM immediately, so the finally block never runs.
  • This is the standard answer to "Does finally always run?": almost always, except when the JVM stops first, as here.

With return in try, the value is saved, finally runs, then the method returns. A return inside finally overrides that value, so never return from finally. It does not run after System.exit(). try-with-resources closes resources declared in try (...) automatically, in reverse order, before catch and finally.

Revise: Finally block rules (opens in a new tab).

Predict the output

Predict the finally output

Read each snippet and pick what it prints.

Round 1 of 3

public class Round1 {
static int f() {
try {
return 1;
} finally {
System.out.print("F ");
}
}
public static void main(String[] args) {
System.out.println(f());
}
}

Custom exceptions and multi-catch

Multi-catch handles several unrelated exception types in one catch block, written with a vertical bar: catch (NumberFormatException | ArithmeticException e). The types must not be parent and child.

A custom exception carries a clear name and useful data. This program defines one, throws it, and uses multi-catch for two unrelated errors.

Example 5 · A custom exception and multi-catch

UpiWallet.javaJava
class InsufficientBalanceException extends Exception {    private final int shortBy;
    InsufficientBalanceException(int shortBy) {        super("Short by Rs " + shortBy);        this.shortBy = shortBy;    }
    int getShortBy() {        return shortBy;    }}
public class UpiWallet {    static int balance = 500;
    static void pay(int amount) throws InsufficientBalanceException {        if (amount > balance) {            throw new InsufficientBalanceException(amount - balance);        }        balance -= amount;        System.out.println("Paid Rs " + amount + ", balance Rs " + balance);    }
    static int share(String bill, String people) {        return Integer.parseInt(bill) / Integer.parseInt(people);    }
    public static void main(String[] args) {        try {            pay(200);            pay(450);        } catch (InsufficientBalanceException e) {            System.out.println("Payment failed: " + e.getMessage() + " (add Rs " + e.getShortBy() + ")");        }
        String[][] inputs = {{"900", "3"}, {"900", "0"}, {"nine", "3"}};        for (String[] in : inputs) {            try {                System.out.println("Share: Rs " + share(in[0], in[1]));            } catch (NumberFormatException | ArithmeticException e) {                System.out.println("Bad input: " + e.getClass().getSimpleName());            }        }    }}
Output
Paid Rs 200, balance Rs 300
Payment failed: Short by Rs 150 (add Rs 150)
Share: Rs 300
Bad input: ArithmeticException
Bad input: NumberFormatException

What this code does

  • InsufficientBalanceException is checked and carries data (shortBy), so the caller can show a precise message instead of a generic error.
  • The multi-catch handles a division by zero and a bad number in one block; the two types are unrelated, so they may be combined.

A custom exception extends Exception (checked) or RuntimeException (unchecked), with a clear name, a message, a constructor that accepts a cause, and fields for useful data such as how much a payment was short by. javac rejects related types in multi-catch with Alternatives in a multi-catch statement cannot be related by subclassing.

Fix the error

Fix the multi-catch

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

Handle a bad number and a missing value in one block.

public class Multi {
public static void main(String[] args) {
try {
Integer.parseInt("x");
} catch (NumberFormatException | IllegalArgumentException e) {
System.out.println("bad number");
}
}
}

Error

Multi.java:5: error: Alternatives in a multi-catch statement cannot be related by subclassing
        } catch (NumberFormatException | IllegalArgumentException e) {
                                         ^
  Alternative NumberFormatException is a subclass of alternative IllegalArgumentException

Traps: broad catch, swallowing, catch order

Exception chaining wraps a low-level exception as the cause of a higher-level one, such as new ReportException("Could not load marks", e). The stack trace then shows both, so no detail is lost.

Three habits lose marks: swallowing, wrapping without the cause, and wrong catch order. This program shows a swallowing method, a method that wraps with the cause, and a correct catch order.

Example 6 · Swallowing vs wrapping, and catch order

CatchTraps.javaJava
public class CatchTraps {    static int parseSwallow(String s) {        try {            return Integer.parseInt(s);        } catch (Exception e) {            return 0;                       // hides the problem: bad data becomes 0        }    }
    static int parseOrExplain(String s) {        try {            return Integer.parseInt(s.trim());        } catch (NumberFormatException e) {            throw new IllegalArgumentException("Bad marks value: '" + s + "'", e);        }    }
    public static void main(String[] args) {        System.out.println("swallowed: " + parseSwallow("8O"));
        try {            parseOrExplain("8O");        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());            System.out.println("cause: " + e.getCause().getClass().getSimpleName());        }
        try {            Object o = "ninety";            Integer marks = (Integer) o;            System.out.println(marks);        } catch (ClassCastException e) {        // specific first            System.out.println("specific catch: ClassCastException");        } catch (RuntimeException e) {          // general after            System.out.println("general catch");        }    }}
Output
swallowed: 0
Bad marks value: '8O'
cause: NumberFormatException
specific catch: ClassCastException

What this code does

  • parseSwallow turns a typo (8O) into a silent 0 mark: the worst outcome. parseOrExplain fails loudly with a clear message and keeps the original exception as the cause.
  • Catches are checked top to bottom, so the specific ClassCastException comes first. Swapping the two blocks gives the compile error exception ClassCastException has already been caught.

Catching Exception everywhere also hides bugs like NullPointerException. Swallowing, an empty catch, lets the program continue in a wrong state with no trace. A general catch before a specific one does not compile: exception NumberFormatException has already been caught. Catch what you can handle, from specific to general, and wrap with the original as the cause.

Find the bug

Find the exception-handling bug

Each snippet has one wrong line. Tap it, then check the fix.

Handle a bad number and any other runtime error.

Round 1 of 3

Next step

Check your understanding

12 quick questions