Home
10Exception Handling
10

Topic 10 of 13 · Lectures 15–18

Exception Handling

What happens when something goes wrong at run time, the exception class hierarchy, try, catch, finally, throw and throws, and writing your own exception classes.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

A user types “abc” where your program expects a number. Should the whole program crash?

Without exception handling, yes: Java prints a stack trace and stops. With it, you can catch the problem, explain it to the user and carry on.

Java separates the code that does the work from the code that handles problems, and the compiler even forces you to deal with some kinds of failure.

Outline · Lectures 15–18

Topics in this chapter

Select a topic to jump to the slide that explains it.

  1. What is an exception
  2. Exception types: checked, unchecked, errors
  3. try, catch and finally
  4. Multiple catch clauses
  5. throw and throws
  6. Custom exceptions

Concept 1 of 6

What is an exception?

public class Crash {
    static int avg(int[] a) { return sum(a) / a.length; }
    static int sum(int[] a) { int s = 0; for (int x : a) s += x; return s; }
    public static void main(String[] args) {
        System.out.println(avg(new int[]{4, 6}));
        System.out.println(avg(new int[]{}));
        System.out.println("never printed");
    }
}

Concept 1 of 6

What is an exception? (cont.)

Output
5
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Crash.avg(Crash.java:2)
	at Crash.main(Crash.java:6)
  • An exception is an object that describes an error that happened while the program was running.
  • When it is thrown, normal execution stops and Java looks back through the call stack for a matching handler.
  • If no method handles it, the thread ends and the stack trace shows where it happened — read it from the top.

Concept 2 of 6

Types of exceptions

Everything that can be thrown extends Throwable.

Types of exceptions

KindExamplesCompiler forces handling?
Checked (Exception, not Runtime)IOException, FileNotFoundException, SQLException, InterruptedExceptionYes — catch it or declare throws
Unchecked (RuntimeException)ArithmeticException, NullPointerException, ArrayIndexOutOfBounds, NumberFormatExceptionNo — usually a bug to fix
ErrorOutOfMemoryError, StackOverflowErrorNo — do not try to recover

Concept 3 of 6

try, catch and finally

Where execution goes after each part.

try, catch and finally

try {
    int n = Integer.parseInt(text);   // may throw
    System.out.println(100 / n);      // may throw
} catch (NumberFormatException e) {
    System.out.println("Not a number");
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
} finally {
    System.out.println("done");       // always runs
}
  • try wraps code that may throw. The rest of the try block is skipped after an exception.
  • catch handles one type (and its subclasses). The first matching catch runs.
  • finally runs whether or not an exception occurred — even after return. Use it for clean-up.

Step through the code

Trace: three inputs, three paths

Choose an input above the code, then step through. Compare which lines run for "10", "0" and "abc".

Step through the code

Trace: three inputs, three paths (cont.)

Interactive

Catch-clause matcher

Concept 4 of 6

Multiple catch clauses and multi-catch

try {
    ...
} catch (FileNotFoundException e) {    // most specific first
    System.out.println("Missing file");
} catch (IOException e) {              // then its superclass
    System.out.println("I/O problem");
} catch (NumberFormatException | ArithmeticException e) {
    System.out.println("Bad data: " + e.getMessage());
} catch (Exception e) {                // catch-all last
    e.printStackTrace();
}
  • Order catches from specific to general. A superclass catch before its subclass makes the later one unreachable — a compile error.
  • Multi-catch (A | B) shares one handler; A and B must not be related by inheritance.
  • Useful methods of every exception: getMessage(), toString(), printStackTrace().

Concept 5 of 6

throw and throws

static void setAge(int age) {
    if (age < 0)
        throw new IllegalArgumentException("age < 0: " + age);
    this.age = age;
}

static String firstLine(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
throwthrows
WhatA statement that throws one exception object nowPart of a method header listing exceptions it may pass on
WhereInside a method bodyAfter the parameter list
Followed byAn object: throw new X(...)Class names: throws IOException, SQLException

Step through the code

Trace: an exception travels up the stack

level3 throws; level2 does not catch it, but its finally still runs; main catches it. Watch the frames disappear.

Step through the code

Trace: an exception travels up the stack (cont.)

Code example

Creating your own exceptions

class InsufficientFundsException extends Exception { // checked private final double shortBy; InsufficientFundsException(double shortBy) { super("Insufficient funds: short by " + shortBy); this.shortBy = shortBy; } double getShortBy() { return shortBy; } } class Account { private double balance = 500; void withdraw(double amt) throws InsufficientFundsException { if (amt > balance) throw new InsufficientFundsException(amt - balance); balance -= amt; System.out.println("Withdrew " + amt + ", left " + balance); } } Account acc = new Account(); try { acc.withdraw(200); acc.withdraw(450); acc.withdraw(10); } catch (InsufficientFundsException e) { System.out.println(e.getMessage()); }
Output
Withdrew 200.0, left 300.0
Insufficient funds: short by 150.0
  • Extend Exception for a checked exception, RuntimeException for an unchecked one.
  • Pass a message to super(msg); add fields for extra details.

Step through the code

Trace: throwing a custom exception

A custom exception is an ordinary object. Watch it get created, thrown, and caught two frames up.

Step through the code

Trace: throwing a custom exception (cont.)

Code example

try-with-resources

try (BufferedReader br = new BufferedReader(new FileReader("marks.txt"))) {
    String line;
    int total = 0;
    while ((line = br.readLine()) != null)
        total += Integer.parseInt(line.trim());
    System.out.println("Total = " + total);
} catch (FileNotFoundException e) {
    System.out.println("File missing: " + e.getMessage());
} catch (IOException | NumberFormatException e) {
    System.out.println("Bad data: " + e);
}
Output (marks.txt holds 78, 91 and 64)
Total = 233

Code example

try-with-resources (cont.)

  • Resources declared in try ( … ) are closed automatically at the end, in reverse order, even if an exception occurs.
  • Works with any class that implements AutoCloseable: files, sockets, database connections, Scanner.

Concept 6 of 6

Good exception habits

DoAvoid
Catch the most specific type you can actually handle.catch (Exception e) {} — silently swallowing every error.
Validate arguments and throw IllegalArgumentException with a clear message.Using exceptions for normal control flow (e.g. to leave a loop).
Use try-with-resources for files and connections.Closing resources by hand and forgetting the error path.
Let exceptions propagate (throws) when the caller knows better how to react.Catching and printing, then continuing with broken data.

Worked example 1 of 3

Worked example 1

What is printed?
try { System.out.print("A"); int x = 5 / 0; System.out.print("B"); }
catch (ArithmeticException e) { System.out.print("C"); }
finally { System.out.print("D"); } System.out.print("E");
Show the solution
ACDE. B is skipped; the catch handles the exception; finally always runs; the program continues.

Worked example 2 of 3

Worked example 2

What does f() return? static int f() { try { return 1; } finally { System.out.print("F"); } }
Show the solution
It prints F and returns 1. finally runs just before the method actually returns.

Worked example 3 of 3

Worked example 3

Make readScore keep asking until the user types a valid integer.
Show the solution
static int readScore(Scanner in) {
    while (true) {
        try {
            return Integer.parseInt(in.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("Please type a whole number.");
        }
    }
}

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. Classify as checked or unchecked: FileNotFoundException, NullPointerException, SQLException, NumberFormatException.
Show the answer
Checked, unchecked, checked, unchecked.
2. Why is catch (Exception e) followed by catch (IOException e) a compile error?
Show the answer
IOException is a subclass of Exception, so the second catch can never be reached.
3. Write a method sqrt(double x) that throws IllegalArgumentException for negative x.
Show the answer
static double sqrt(double x) {
    if (x < 0) throw new IllegalArgumentException("negative: " + x);
    return Math.sqrt(x);
}

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. When does a finally block NOT run?
Show the answer
Practically only if the JVM stops (System.exit, crash, power loss) or the thread is killed while inside try/catch.
5. Create an unchecked exception InvalidMarksException.
Show the answer
class InvalidMarksException extends RuntimeException {
    InvalidMarksException(String msg) { super(msg); }
}
6. What does the stack trace line at Main.main(Main.java:14) tell you?
Show the answer
The exception passed through method main of class Main, at line 14 of Main.java.

Check yourself

Quiz

Summary

Summary

  • An exception is an object describing a run-time error; uncaught ones end the thread with a stack trace.
  • Checked exceptions must be caught or declared; unchecked (RuntimeException) and Errors need not be.
  • try runs risky code, the first matching catch handles it, finally always runs.
  • throw raises an exception object; throws declares what a method may pass on.
  • Custom exceptions extend Exception or RuntimeException; try-with-resources closes resources automatically.