SyntaxPilot
Courses/Java/Lesson 26

Java · Lesson 26 of 51 · 12 min

Exceptions: try, catch, finally, checked vs unchecked

queued

These are the notes for Java episode 26. In episode 25 our bank's transfer just returned false when something went wrong: easy to ignore, and it never said why. Today we meet Java's real answer to problems that happen while a program runs: exceptions. We read a stack trace, handle problems with try and catch, clean up with finally, and learn why the compiler forces you to handle some exceptions (checked) but not others (unchecked). Every example was run with javac 21.

The problem: the chai bill that crashes

Friends at a tapri (a roadside tea stall) run up a bill of 840 rupees. The owner's program divides the bill by the number of people typed in. Users type anything: 0 by mistake, or four in words.

public class Main {
    public static void main(String[] args) {
        int bill = 840;
        String input = "0";
        int people = Integer.parseInt(input);
        System.out.println("Each pays: " + bill / people);
        System.out.println("Thank you, visit again!");
    }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.main(Main.java:6)

Dividing a whole number by zero has no answer, so Java stops the program. And Thank you, visit again! never prints: a crash skips everything after it.

An exception is a problem that happens while the program is running (at runtime). It is different from a compile error, which the compiler finds before the program ever starts.

The obvious fix that fails: return -1

Check first, and agree that -1 means "error":

public class Main {
    static int split(int bill, int people) {
        if (people == 0) return -1;   // -1 means "error"
        return bill / people;
    }
    public static void main(String[] args) {
        System.out.println("Each pays: " + split(840, 4));
        System.out.println("Each pays: " + split(840, 0));
    }
}
Each pays: 210
Each pays: -1

No crash, but the program printed the error code as if it were money. The caller forgot to check, and nothing forced it to.

Why error codes fail:

  1. -1 looks like a normal number, so it gets used as one.
  2. Every caller must remember to check, every time.
  3. It says that something failed, not why.
  4. Sometimes -1 is a real answer (a temperature, an overdrawn balance).

We need a signal that can't be silently ignored and carries a reason. That is an exception.

The idea: a fire alarm

In a building In Java
Someone pulls the fire alarm; work on that floor stops an exception is thrown; the method stops
The alarm rings floor by floor up to the security desk the exception travels up through the calling methods
The guard handles it, everyone else carries on a catch block handles it; the program continues
Emergency lights come on, fire or false alarm a finally block always runs

Reading a stack trace

public class Main {
    static int split(int bill, int people) {
        return bill / people;
    }
    static void printBill(int people) {
        System.out.println("Each pays: " + split(840, people));
    }
    public static void main(String[] args) {
        printBill(4);
        printBill(0);
        System.out.println("Thank you, visit again!");
    }
}
Each pays: 210
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.split(Main.java:3)
    at Main.printBill(Main.java:6)
    at Main.main(Main.java:10)

The lines starting with at are the stack trace: the chain of method calls that were running when the exception happened (the call stack from episode 12).

  • Read it top-down. The first line is where it broke: split, line 3.
  • Each next line is the caller: printBill line 6, then main line 10.
  • Nobody caught the exception, so it reached the top of main and the JVM stopped the program.
  • Tip: start debugging at the first line that points to your code.

try and catch

public class Main {
    public static void main(String[] args) {
        int bill = 840;
        String[] inputs = { "4", "0", "four" };
        for (String input : inputs) {
            try {
                int people = Integer.parseInt(input);
                System.out.println("Each pays: " + bill / people);
            } catch (ArithmeticException e) {
                System.out.println("Can't split among 0 people");
            } catch (NumberFormatException e) {
                System.out.println("Not a number: " + e.getMessage());
            }
        }
        System.out.println("Thank you, visit again!");
    }
}
Each pays: 210
Can't split among 0 people
Not a number: For input string: "four"
Thank you, visit again!
  • try { ... } wraps the risky code: "run this, and if an exception is thrown, jump to a matching catch instead of dying".
  • Each catch (Type e) names the kind of exception it handles. e is a variable holding the exception object.
  • e.getMessage() gives the reason text; printing e itself gives the class name plus the message.
  • When a line inside try throws, the rest of the try block is skipped; Java runs the matching catch and then carries on after the whole try/catch.
  • NumberFormatException is what Integer.parseInt throws for text that isn't a number.

Catch order: specific first

try {
    int x = 840 / 0;
} catch (Exception e) {
    System.out.println("Something failed");
} catch (ArithmeticException e) {
    System.out.println("Divided by zero");
}
Main.java:7: error: exception ArithmeticException has already been caught
        } catch (ArithmeticException e) {
          ^
1 error

Catch blocks are checked top to bottom and the first match wins. Exception is a parent of ArithmeticException, so the second catch could never run, and Java refuses unreachable code. Put specific exceptions first, general ones last.

Multi-catch

When two exceptions need the same handling, join them with |:

public class Main {
    public static void main(String[] args) {
        String[] inputs = { "0", "four" };
        for (String input : inputs) {
            try {
                System.out.println(840 / Integer.parseInt(input));
            } catch (ArithmeticException | NumberFormatException e) {
                System.out.println("Bad input: " + e);
            }
        }
    }
}
Bad input: java.lang.ArithmeticException: / by zero
Bad input: java.lang.NumberFormatException: For input string: "four"

finally: code that always runs

public class Main {
    static int split(int bill, int people) {
        try {
            System.out.println("Shop open");
            return bill / people;
        } finally {
            System.out.println("Shutter down");
        }
    }
    public static void main(String[] args) {
        System.out.println("Each pays: " + split(840, 4));
        System.out.println("Each pays: " + split(840, 0));
    }
}
Shop open
Shutter down
Each pays: 210
Shop open
Shutter down
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.split(Main.java:5)
    at Main.main(Main.java:12)
  • finally runs after try (and catch), no matter what: normal end, return, or an exception.
  • The return waits for finally: "Shutter down" prints before "Each pays: 210".
  • Even an exception that is not caught runs finally on its way out.
  • try with only finally (no catch) is allowed.
  • Use it for clean-up: closing files, network and database connections. (Episode 27 shows an even better tool: try-with-resources.)

With all three together:

try {
    System.out.println("Each pays: " + 840 / 0);
} catch (ArithmeticException e) {
    System.out.println("Caught: " + e.getMessage());
} finally {
    System.out.println("Bill closed");
}
System.out.println("Next customer");
Caught: / by zero
Bill closed
Next customer

The exception family tree

Exceptions are classes, organised with inheritance (episode 18):

Throwable                  anything that can be thrown
├── Error                  serious JVM problems: OutOfMemoryError, StackOverflowError
└── Exception              problems a program can handle
    ├── IOException, FileNotFoundException, ...    (checked)
    └── RuntimeException                           (unchecked)
        ├── ArithmeticException
        ├── NullPointerException
        ├── ArrayIndexOutOfBoundsException
        └── IllegalArgumentException
            └── NumberFormatException
  • Unchecked = RuntimeException and its children, plus Error. The compiler does not force you to handle them. They usually mean a bug in your own code.
  • Checked = every other Exception. The compiler checks that you either catch it or declare it with throws. They usually come from outside your code: a missing file, a network that's down.
  • You normally don't catch Errors: the stack overflow from too much recursion (episode 12) is one.

Checked exceptions in action

import java.io.FileReader;

public class Main {
    public static void main(String[] args) {
        FileReader menu = new FileReader("menu.txt");
        System.out.println("Menu opened");
    }
}
Main.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        FileReader menu = new FileReader("menu.txt");
                          ^
1 error

The file might not exist at any moment, and that's not a bug in your code, so Java makes you decide in advance. Handle it:

import java.io.FileReader;
import java.io.FileNotFoundException;

public class Main {
    public static void main(String[] args) {
        try {
            FileReader menu = new FileReader("menu.txt");
            System.out.println("Menu opened");
        } catch (FileNotFoundException e) {
            System.out.println("No menu today: " + e.getMessage());
        }
        System.out.println("Serving chai anyway");
    }
}
No menu today: menu.txt (No such file or directory)
Serving chai anyway

The other choice, declaring it (throws FileNotFoundException), passes the alarm up to the caller. That's episode 27.

The empty-catch trap

try {
    int people = Integer.parseInt("0");
    System.out.println(840 / people);
} catch (Exception e) {
}
System.out.println("All good!");
All good!

The division by zero happened, and the empty catch hid it. This is called swallowing an exception. At the very least print it (System.out.println(e)); better, handle it properly or let it travel up.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
Dividing by an unchecked 0 Exception in thread "main" java.lang.ArithmeticException: / by zero unhandled runtime exception check first, or catch ArithmeticException
parseInt on text java.lang.NumberFormatException: For input string: "four" the text isn't a number catch NumberFormatException
General catch before specific error: exception ArithmeticException has already been caught the second catch is unreachable specific first, general last
Ignoring a checked exception error: unreported exception FileNotFoundException; must be caught or declared to be thrown checked exceptions must be handled try/catch, or throws
Empty catch block no message at all (All good!) the exception was swallowed print it, handle it, or let it travel up
Returning -1 for errors no error: Each pays: -1 error codes look like normal values throw an exception (episode 27)

Mini project: a safe bill splitter

Read lines like 840 4, 840 0, 840 four, abc 3 and print each person's share. Bad lines must not stop the program.

public class Main {
    public static void main(String[] args) {
        String[] lines = { "840 4", "840 0", "840 four", "abc 3", "900" };
        int ok = 0, bad = 0;
        for (String line : lines) {
            try {
                String[] parts = line.split(" ");
                int bill = Integer.parseInt(parts[0]);
                int people = Integer.parseInt(parts[1]);
                System.out.println(line + " -> each pays " + bill / people);
                ok++;
            } catch (ArithmeticException e) {
                System.out.println(line + " -> nobody to pay");
                bad++;
            } catch (NumberFormatException e) {
                System.out.println(line + " -> not a number: " + e.getMessage());
                bad++;
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println(line + " -> missing a value");
                bad++;
            } finally {
                System.out.println("  (line checked)");
            }
        }
        System.out.println(ok + " bills split, " + bad + " rejected");
    }
}
840 4 -> each pays 210
  (line checked)
840 0 -> nobody to pay
  (line checked)
840 four -> not a number: For input string: "four"
  (line checked)
abc 3 -> not a number: For input string: "abc"
  (line checked)
900 -> missing a value
  (line checked)
1 bills split, 4 rejected

Practice

  1. Read an age with Integer.parseInt; print "Not a valid age" for bad text.
  2. Print arr[5] on a 3-item array inside try/catch. Which exception is it?
  3. Write a method with a finally that prints done. Call it once with an error and once without.
  4. Name three checked and three unchecked exceptions.
Solutions

1.

String text = "twenty";
try {
    int age = Integer.parseInt(text);
    System.out.println("Age: " + age);
} catch (NumberFormatException e) {
    System.out.println("Not a valid age");
}

2. ArrayIndexOutOfBoundsException (unchecked). Its message is Index 5 out of bounds for length 3.

int[] arr = { 1, 2, 3 };
try {
    System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught: " + e.getMessage());
}

3. done prints both times; with the error, the exception continues after finally unless it's caught.

static void work(int d) {
    try {
        System.out.println(10 / d);
    } finally {
        System.out.println("done");
    }
}

4. Checked: IOException, FileNotFoundException, InterruptedException (also SQLException, ClassNotFoundException). Unchecked: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, IllegalArgumentException.

Quick quiz

try {
    System.out.print("A ");
    int x = 10 / 0;
    System.out.print("B ");
} catch (ArithmeticException e) {
    System.out.print("C ");
} finally {
    System.out.print("D ");
}
System.out.print("E");

A) A B D E B) A C D E C) A C E D) A B C D E

Answer

B. 10 / 0 throws, so B is skipped. The catch prints C, finally always prints D, and since the exception was handled the program continues to E.

A C D E

Interview questions

  1. What is an exception? An object representing a problem at runtime; throwing it stops the current method and travels up the call stack until a matching catch handles it, or the program ends.
  2. Checked vs unchecked? Checked exceptions (subclasses of Exception but not RuntimeException) must be caught or declared; the compiler enforces it. Unchecked ones (RuntimeException, Error) don't need to be.
  3. Error vs Exception? Error means a serious JVM problem (out of memory, stack overflow) that applications shouldn't try to handle; Exception is for conditions a program can handle.
  4. Does finally run if try has a return? Yes; the return value is held until finally finishes. It's skipped only in rare cases such as System.exit() or the JVM crashing.
  5. Why must specific catch blocks come first? The first matching catch wins; a parent type first would make the child's catch unreachable, which is a compile error.
  6. What is multi-catch? catch (A | B e) handles several unrelated exception types with one block.
  7. Why is an empty catch block bad? It hides the failure; the program continues in a wrong state with no clue for debugging.
  8. What does a stack trace show? The exception type, its message, and the chain of method calls (with file and line) that were running, innermost first.

Glossary

Term Meaning Example
Exception An object describing a problem at runtime ArithmeticException
Runtime While the program is running (not compiling) dividing by an input of 0
Throw To raise an exception, stopping the current code Java throws on 840 / 0
Catch A block that handles a specific exception type catch (ArithmeticException e)
try block Code that might throw, watched by the catches after it try { ... }
finally block Code that always runs after try/catch closing the shutter
Stack trace The list of method calls active when the exception happened at Main.split(Main.java:3)
Call stack The methods currently running, each called by the one below main → printBill → split
Propagation An exception moving up to the caller when not caught split → printBill → main
Error code A special return value meaning failure return -1
getMessage() Returns the exception's reason text / by zero
Multi-catch One catch for several types, joined with \| catch (A \| B e)
Throwable The root class of everything that can be thrown parent of Error and Exception
Error Serious JVM problems you don't catch OutOfMemoryError, StackOverflowError
RuntimeException Parent of unchecked exceptions, usually bugs NullPointerException
Checked exception Must be caught or declared; the compiler checks FileNotFoundException
Unchecked exception Not checked by the compiler ArithmeticException
ArithmeticException Thrown for integer division by zero 840 / 0
NumberFormatException Thrown when text can't be parsed as a number Integer.parseInt("four")
FileReader A class that opens a file for reading characters new FileReader("menu.txt")
Swallowing an exception Catching it and doing nothing catch (Exception e) { }

Summary

  • An exception is a problem at runtime; uncaught, it stops the program and prints a stack trace (read it top-down).
  • Error codes like -1 or false are easy to ignore and say nothing about why.
  • try/catch handles a problem and lets the program carry on; specific catches first, or multi-catch with |.
  • finally always runs, even after return or an uncaught exception: use it for clean-up.
  • Throwable → Error / Exception → RuntimeException. Unchecked: RuntimeException + Error. Checked: everything else, which must be caught or declared.
  • Never leave a catch block empty.
  • Next: our bank throws its own InsufficientFundsException, we learn throw vs throws, and try-with-resources closes files for us. Episode 27.