Teacher Guide: Exception Handling

Student page: Exception Handling IB Syllabus: B2.1.3 Estimated periods: 1–2 (90 min each) Prerequisites: Variables & Data Types, Selection

Contents

  1. Lesson Plans
    1. Period 1: try-catch-finally Basics
    2. Period 2 (if needed): Advanced Patterns
  2. Differentiation
    1. Supporting weaker students
    2. Extending stronger students
  3. Answer Keys
    1. Core 1: Safe Division
    2. Core 2: Safe Input
    3. Core 3: With Finally
    4. Extension 4: Retry Loop
    5. Extension 5: Array Bounds
    6. Challenge 6: Calculator with Error Handling
  4. Trace Exercise Answer Key
  5. Quick Code Check Answer Key
  6. Code Completion Answer Key
  7. Spot the Bug Answer Key
  8. Output Prediction Answer Key
  9. Integration Notes
    1. Additional Resources

Lesson Plans

Period 1: try-catch-finally Basics

Phase Time Activity Student Page Section
Warm-up 10 min Run area-of-circle and type “hello” — watch the crash
Teach 25 min try/catch/finally structure, common exception types Key Concepts
Practice 40 min Core #1-3 (Safe division, Safe input, With finally) Practice Exercises
Wrap-up 15 min Quick Code Check + “hotel checkout” analogy recap Quick Code Check

Teaching notes:

  • Crash first — let them see InputMismatchException before explaining try-catch. The surprise creates a lasting memory.
  • Table on board: try = “what might fail?”, catch = “what if it does?”, finally = “what always happens?”
  • Hotel analogy for finally: whether the trip goes well or is cancelled, you still check out of the hotel room. finally is the checkout.
  • When showing the common exception types table, ask students to predict when each one occurs before revealing the answer. This builds the habit of anticipating runtime failures.

Period 2 (if needed): Advanced Patterns

Phase Time Activity Student Page Section
Warm-up 10 min Review: “Name 3 common exceptions and when they occur”
Teach 15 min Retry loop pattern, multiple catch blocks Worked Examples
Practice 50 min Extension #4-5, Challenge #6 Practice Exercises
Wrap-up 15 min Trace exercise + discuss file I/O connection Trace Exercise

Teaching notes:

  • The retry loop pattern (Example 4 on the student page) is the most practically useful pattern. Emphasize the scanner.nextLine() buffer-clearing step — forgetting it causes an infinite loop.
  • Multiple catch blocks: demonstrate that Java checks them top to bottom and runs the first match. Order matters when exception types are related by inheritance (not examinable, but worth mentioning briefly).
  • End with the trace exercise to reinforce execution flow: try → exception → skip remaining try → catch → finally → continue.

Differentiation

Supporting weaker students

Strategy When to use Example
try-catch template Student can’t remember the structure Provide skeleton: try { /* risky code */ } catch (___Exception e) { /* handle */ }
Exception matching worksheet Confuses exception types Match: “divide by zero” → ArithmeticException, “enter text for number” → InputMismatchException
Reduce to Core only Overwhelmed by catch types Focus on Core #1-2, skip #3 initially
Visual flowchart Can’t trace exception flow Draw: try → success → skip catch → finally vs try → fail → catch → finally
Annotated code Struggles to read try-catch blocks Provide a printout with arrows showing “execution jumps here” when exception occurs

Extending stronger students

Strategy When to use Example
Multiple catch blocks Finishes Core early Handle ArithmeticException and InputMismatchException separately in one try block
Custom error messages After Core #2 Print the exception’s getMessage() alongside the friendly message
Challenge #6 Extended learners Full calculator with 3 different error types
File I/O preview After all exercises “What exceptions might occur when reading a file?” — connects to B2.5
Exception hierarchy research Strong finishers Research: why does catching Exception hide bugs? What is the difference between checked and unchecked exceptions?

Answer Keys

Core 1: Safe Division

Show answer
import java.util.Scanner;

public class SafeDivision {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int a = scanner.nextInt();
        System.out.print("Enter second number: ");
        int b = scanner.nextInt();
        try {
            int result = a / b;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero.");
        }
        scanner.close();
    }
}

Expected output (b=0): Error: Cannot divide by zero. Expected output (a=10, b=3): Result: 3

Common mistakes:

  • Catching generic Exception instead of ArithmeticException — overly broad catch hides other bugs
  • Putting Scanner input inside the try block unnecessarily — the try should wrap only the risky division, not the input reading
  • Forgetting scanner.close() — not an error, but good practice

Core 2: Safe Input

Show answer
import java.util.Scanner;

public class SafeInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        try {
            int number = scanner.nextInt();
            System.out.println("You entered: " + number);
        } catch (java.util.InputMismatchException e) {
            System.out.println("Error: That is not a valid integer.");
        }
        scanner.close();
    }
}

Expected output (input “42”): You entered: 42 Expected output (input “hello”): Error: That is not a valid integer.

Common mistakes:

  • Forgetting to import or fully qualify InputMismatchException — either import java.util.InputMismatchException; at the top or use the fully qualified name in the catch
  • Declaring number inside the try block and trying to use it after the try-catch — scope issue

Core 3: With Finally

Show answer
import java.util.Scanner;

public class WithFinally {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int a = scanner.nextInt();
        System.out.print("Enter second number: ");
        int b = scanner.nextInt();
        try {
            int result = a / b;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero.");
        } finally {
            System.out.println("Calculation attempt complete.");
        }
        scanner.close();
    }
}

Expected output (b=0):

Error: Cannot divide by zero.
Calculation attempt complete.

Expected output (a=10, b=2):

Result: 5
Calculation attempt complete.

Key point: The finally block runs in BOTH cases — this is the core concept students must demonstrate understanding of.

Extension 4: Retry Loop

Show answer
import java.util.Scanner;

public class RetryLoop {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean valid = false;
        int number = 0;
        while (!valid) {
            System.out.print("Enter an integer: ");
            try {
                number = scanner.nextInt();
                valid = true;
            } catch (java.util.InputMismatchException e) {
                System.out.println("Invalid input. Try again.");
                scanner.nextLine(); // clear the invalid input from buffer
            }
        }
        System.out.println("You entered: " + number);
        scanner.close();
    }
}

Sample interaction:

Enter an integer: hello
Invalid input. Try again.
Enter an integer: 3.5
Invalid input. Try again.
Enter an integer: 7
You entered: 7

Common mistakes:

  • Forgetting scanner.nextLine() after catching InputMismatchException — this is the #1 mistake. The invalid token stays in the Scanner buffer, so nextInt() immediately fails again on the next loop iteration, causing an infinite loop. Emphasize buffer clearing.
  • Using scanner.next() instead of scanner.nextLine()next() only clears one token, while nextLine() clears the entire remaining line including the newline character

Marking notes: This is the single most important pattern to get right. If a student’s code works but is missing scanner.nextLine(), it will appear to work with some inputs but loop infinitely with others. Test with non-numeric input to verify.

Extension 5: Array Bounds

Show answer
import java.util.Scanner;

public class ArrayBounds {
    public static void main(String[] args) {
        int[] data = {10, 20, 30, 40, 50};
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an index (0-4): ");
        try {
            int index = scanner.nextInt();
            System.out.println("Value at index " + index + ": " + data[index]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index out of bounds. Valid range is 0-4.");
        }
        scanner.close();
    }
}

Expected output (index=2): Value at index 2: 30 Expected output (index=7): Error: Index out of bounds. Valid range is 0-4. Expected output (index=-1): Error: Index out of bounds. Valid range is 0-4.

Common mistakes:

  • Using wrong exception type — IndexOutOfBoundsException works too (it is the parent class), but ArrayIndexOutOfBoundsException is more specific and preferred
  • Not testing with negative indices — students often only test with indices that are too large, but negative indices also throw the exception

Challenge 6: Calculator with Error Handling

Show answer
import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("Enter first number: ");
            double a = scanner.nextDouble();
            System.out.print("Enter operator (+, -, *, /): ");
            String op = scanner.next();
            System.out.print("Enter second number: ");
            double b = scanner.nextDouble();
            double result;
            if (op.equals("+")) {
                result = a + b;
            } else if (op.equals("-")) {
                result = a - b;
            } else if (op.equals("*")) {
                result = a * b;
            } else if (op.equals("/")) {
                if (b == 0) {
                    System.out.println("Error: Cannot divide by zero.");
                    scanner.close();
                    return;
                }
                result = a / b;
            } else {
                System.out.println("Error: Unknown operator '" + op + "'.");
                scanner.close();
                return;
            }
            System.out.println("Result: " + result);
        } catch (java.util.InputMismatchException e) {
            System.out.println("Error: Invalid number input.");
        }
        scanner.close();
    }
}

Common mistakes:

  • Using == instead of .equals() for operator comparison — this is a critical error. == compares memory addresses for Strings, not content. Always use .equals().
  • Not handling all three error types: invalid input, division by zero, unknown operator
  • Using int instead of double for the numbers — acceptable but limits functionality (integer division issue from earlier)

Marking notes: Must handle all 3 error cases: invalid number input (via try-catch), division by zero (via if-check or try-catch), and unknown operator (via else branch). Accept reasonable variations in structure — some students may use nested try-catch blocks, others may use if-checks for division by zero. Both approaches are valid.


Trace Exercise Answer Key

Show answer

Code:

int x = 10;
int y = 0;

try {
    System.out.println("A");
    int result = x / y;
    System.out.println("B");
} catch (ArithmeticException e) {
    System.out.println("C");
} finally {
    System.out.println("D");
}
System.out.println("E");

Trace:

Line Executes? Why
println("A") Yes Before the exception — runs normally
x / y Yes Attempts division, throws ArithmeticException
println("B") No Skipped — after exception in try block
println("C") Yes Catch block runs because ArithmeticException matches
println("D") Yes Finally always runs
println("E") Yes After try-catch-finally, execution continues normally

Complete output: A C D E (each on a separate line)

Teaching tip: Walk through this trace on the board with arrows showing the execution flow. Draw a clear “jump” arrow from the x / y line directly to the catch block, skipping println("B"). This visual makes the control flow intuitive.


Quick Code Check Answer Key

Show answers
Question Correct Answer Key Point
Q1: The finally block runs… C — Always, whether or not an exception occurred This is the defining property of finally
Q2: User types ‘abc’ into nextInt()… B — The catch block runs InputMismatchException is thrown and caught
Q3: What exception does int x = 10 / 0 throw? A — ArithmeticException Note: double division by zero produces Infinity, not an exception
Q4: Multiple catch blocks? D — Yes, each catches a different type; only the matching one runs Java checks catch blocks top to bottom
Q5: Line 2 throws, what about line 3? B — Line 3 is skipped, execution jumps to catch Remaining try-block code after the exception is skipped entirely

Code Completion Answer Key

Show answer
import java.util.Scanner;
import java.util.InputMismatchException;

Scanner input = new Scanner(System.in);
try {
    System.out.print("Enter age: ");
    int age = input.nextInt();
    System.out.println("Age: " + age);
} catch (InputMismatchException e) {
    System.out.println("Please enter a number!");
}

Blanks: try and catch


Spot the Bug Answer Key

Show answer

The bug is on line 2: double b = 0.0;

Explanation: Division by zero with double types does not throw an ArithmeticException. Instead, Java produces Infinity (or -Infinity or NaN). The catch block never runs because no exception is thrown.

Fix options:

  • Check if (b == 0) before dividing and handle it with an if-statement
  • Use int types instead of double — integer division by zero does throw ArithmeticException

Teaching tip: This is a subtle but important distinction. Students often assume all division by zero throws an exception. Only integer division by zero throws ArithmeticException. This is worth demonstrating live — have students run both versions and compare the behavior.


Output Prediction Answer Key

Show answer

Code:

try {
    System.out.println("Start");
    int x = 5 / 0;
    System.out.println("After");
} catch (ArithmeticException e) {
    System.out.println("Caught");
} finally {
    System.out.println("Finally");
}

Output:

Start
Caught
Finally

Explanation:

  1. "Start" prints normally (before the exception)
  2. 5 / 0 throws ArithmeticException
  3. "After" is skipped (remaining try-block code after exception)
  4. "Caught" prints (catch block runs)
  5. "Finally" prints (finally block always runs)

Integration Notes

Item In Class Homework Link
Worked Examples Walk through together Worked Examples
Quick Code Check End of Period 1 Quick Code Check
Core #1-3 Period 1 practice Practice Exercises
Extension #4-5 Period 2 (if available) Or homework Practice Exercises
Challenge #6 Optional extension Practice Exercises
Trace Exercise Period 1 or 2 wrap-up Trace Exercise
GitHub Classroom Due end of week GitHub Classroom

Additional Resources

  • Exception type matching worksheet: Create a two-column matching activity — left column has scenarios (“user types ‘abc’ when asked for age”, “program accesses index 10 of a 5-element array”, “program divides an integer by zero”), right column has exception class names. Good warm-up for Period 2.
  • File I/O preview discussion: “What can go wrong when opening a file?” — the file might not exist (FileNotFoundException), you might not have permission, the file might be corrupted. This connects directly to B2.5 File Processing and motivates why exception handling is taught before file I/O.
  • “Exception or not?” sorting activity: Give students a list of situations and ask them to classify each as “throws an exception” or “does not throw an exception.” Include edge cases like double division by zero (produces Infinity, no exception) to reinforce the Spot the Bug lesson.

Back to top

© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.