Exception Handling

B2.1.3 - Describe how programs use common exception handling techniques.


Key Concepts

Programs can fail at runtime - a user might type text where a number is expected, a file might not exist, or a calculation might divide by zero. Exception handling lets your program respond gracefully instead of crashing.

The try-catch-finally Structure

try {
    // code that might throw an exception
} catch (ExceptionType e) {
    // code that runs if that exception is thrown
} finally {
    // code that ALWAYS runs - cleanup
}
try:
    # code that might raise an exception
    pass
except ValueError:      # Python says "except", not "catch" - name the specific error
    # code that runs if that exception is raised
    pass
finally:
    # code that ALWAYS runs - cleanup
    pass
Block When it runs
try Always - wraps the risky code
catch Only if the specified exception is thrown
finally Always - even if an exception occurred

(Python keywords: try, except, finally - except plays the role of catch.)

The finally block is optional, but when present it always executes - whether the try succeeded or the catch ran. It is used for cleanup tasks like closing files.

Common Exception Types

Exception When it occurs
InputMismatchException Scanner expected a number but got text
ArrayIndexOutOfBoundsException Accessing an index beyond array bounds
ArithmeticException Division by zero (integer)
NullPointerException Calling a method on a null reference
NumberFormatException Converting a non-numeric String to a number
FileNotFoundException Opening a file that doesn’t exist

(Python’s nearest equivalents, top to bottom: ValueError, IndexError, ZeroDivisionError, AttributeError, ValueError again for int("abc"), FileNotFoundError.)


Worked Examples

Example 1: Basic try-catch - Invalid Input

import java.util.Scanner;
import java.util.InputMismatchException;

Scanner input = new Scanner(System.in);

try {
    System.out.print("Enter a whole number: ");
    int number = input.nextInt();
    System.out.println("Double that is: " + (number * 2));
} catch (InputMismatchException e) {
    System.out.println("Error: please enter a valid integer.");
}
try:
    number = int(input("Enter a whole number: "))
    print("Double that is:", number * 2)
except ValueError:      # int() raises ValueError when the text is not a number
    print("Error: please enter a valid integer.")

If user enters 42: prints Double that is: 84 If user enters hello: prints Error: please enter a valid integer.

The program continues running after the catch - it does not crash.


Example 2: try-catch-finally - Guaranteed Cleanup

import java.util.Scanner;
import java.util.InputMismatchException;

Scanner input = new Scanner(System.in);

try {
    System.out.print("Enter a number: ");
    int num = input.nextInt();
    System.out.println("Result: " + (100 / num));
} catch (InputMismatchException e) {
    System.out.println("That's not a number!");
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("Program complete.");
}
try:
    num = int(input("Enter a number: "))
    print("Result:", 100 // num)     # // = whole-number division; 100 // 0 raises ZeroDivisionError
except ValueError:
    print("That's not a number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Program complete.")

Key points:

  • You can have multiple catch blocks for different exception types
  • The finally block prints "Program complete." regardless of what happened
  • If the user enters 0, the ArithmeticException catch runs, then finally runs

Example 3: Division by Zero

int a = 10;
int b = 0;

try {
    int result = a / b;
    System.out.println("Result: " + result);
} catch (ArithmeticException e) {
    System.out.println("Error: cannot divide by zero.");
    System.out.println("Message: " + e.getMessage());
}
a = 10
b = 0

try:
    result = a // b
    print("Result:", result)
except ZeroDivisionError as e:      # "as e" captures the exception object
    print("Error: cannot divide by zero.")
    print("Message:", e)            # Python's wording differs from Java's "/ by zero":
                                    # "integer division or modulo by zero"

Output:

Error: cannot divide by zero.
Message: / by zero

e.getMessage() returns a short description of what went wrong. This is useful for debugging. (Python: write except ZeroDivisionError as e, then print(e) does the same job.)


Example 4: Input Validation Loop with try-catch

Combine exception handling with a loop to keep asking until valid input is provided.

import java.util.Scanner;
import java.util.InputMismatchException;

Scanner input = new Scanner(System.in);
boolean valid = false;
int number = 0;

while (!valid) {
    try {
        System.out.print("Enter an integer: ");
        number = input.nextInt();
        valid = true;
    } catch (InputMismatchException e) {
        System.out.println("Invalid! Please enter a whole number.");
        input.nextLine();  // clear the invalid input from the buffer
    }
}

System.out.println("You entered: " + number);
valid = False
number = 0

while valid == False:
    try:
        number = int(input("Enter an integer: "))
        valid = True
    except ValueError:
        print("Invalid! Please enter a whole number.")
        # no buffer to clear - input() always reads a fresh line

print("You entered:", number)

After an InputMismatchException, the invalid input remains in the Scanner buffer. You must call input.nextLine() to clear it before the next iteration, otherwise the loop runs forever. (Python’s input() has no leftover-buffer problem - there is nothing to clear.)


Example 5: What NOT to Do

// BAD - catching Exception hides all errors
try {
    // lots of code here...
} catch (Exception e) {
    // silently swallows every possible error
}
# BAD - a bare "except:" (or "except Exception:") hides all errors
try:
    # lots of code here...
    pass
except:
    # silently swallows every possible error
    pass

Catch specific exceptions, not Exception. Catching everything makes bugs invisible and programs harder to debug.


Quick Check

Q1. The finally block runs:

Q2. What happens if the user types 'abc' into a nextInt() call wrapped in try-catch?

Q3. What exception does int x = 10 / 0; throw?

Q4. Can a single try block have multiple catch blocks?

Q5. If line 2 of a try block throws an exception, what happens to line 3?


Trace Exercise

Trace this code - determine which lines execute and what is printed.

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");
x = 10
y = 0

try:
    print("A")
    result = x // y      # raises ZeroDivisionError
    print("B")
except ZeroDivisionError:
    print("C")
finally:
    print("D")
print("E")
LineDoes it execute?Why?
println("A") Before the exception
x / y Throws ArithmeticException
println("B") Skipped - after exception in try
println("C") Catch block runs
println("D") Finally always runs
println("E") After try-catch-finally

What is the complete output? Write the letters in the order they print, on one line with a space between them.


Code Completion

This code reads the user’s age from keyboard input and uses a try-catch block to gracefully handle the case where the user types non-numeric text instead of a number. Fill in the missing keywords to complete the exception handling structure.

import java.util.Scanner;
import java.util.InputMismatchException;

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

Spot the Error

This code is supposed to catch division by zero using a try-catch with ArithmeticException, but the catch block never runs. The bug involves a key difference between how Java handles integer vs. floating-point division by zero.

(Python note: this trap is Java-only - in Python, 10.0 / 0.0 raises ZeroDivisionError just like integer division does.)

double a = 10.0;
double b = 0.0;
try {
    double result = a / b;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

What is wrong and how do you fix it?


Predict the Output

This code tests your understanding of execution flow through a complete try-catch-finally block when an exception is thrown mid-way through the try block. Pay attention to which print statements are skipped and which always run.

What does this code print?

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");
}
try:
    print("Start")
    x = 5 // 0
    print("After")
except ZeroDivisionError:
    print("Caught")
finally:
    print("Finally")
Expected: Start
Caught
Finally

Practice Exercises

Core

  1. Safe division - Read two integers. Use try-catch to handle division by zero and print an error message instead of crashing.

  2. Safe input - Read an integer using Scanner. If the user enters non-numeric text, catch the InputMismatchException and print a friendly message.

  3. With finally - Modify exercise 1 to include a finally block that prints “Calculation attempt complete.”

Extension

  1. Retry loop - Keep asking the user for a valid integer until they enter one. Use try-catch inside a while loop. Remember to clear the buffer with nextLine() after an invalid input.

  2. Array bounds - Create an array of 5 elements. Ask the user for an index and try to access that element. Catch ArrayIndexOutOfBoundsException if the index is invalid.

Challenge

  1. Calculator with error handling - Build a simple calculator that reads two numbers and an operator (+, -, *, /). Handle: invalid number input, division by zero, and unknown operators - each with a specific error message.

GitHub Classroom

Exception Handling (Java)
Practice try-catch-finally, handling InputMismatchException and ArithmeticException.

A class assignment on GitHub Classroom: use it when your teacher has set it. It needs a free GitHub account.

Working in the Codespace

  1. Accept and open. Accept the assignment above, open the link in the email from GitHub, then press Open in Codespace. In Java, change the status bar from Lightweight to Standard mode.
  2. Write and check. Open src/ExceptionHandling.java and complete each TODO. Press Run and compare the output with the comments, or run bash run-tests.sh in the Terminal.
  3. Submit. In Source Control, write a message, press Commit, then Sync Changes. Your teacher’s feedback arrives as a pull request called Feedback.

The full Codespace guide, with pictures


Connections

Prerequisites:

Related Topics:

  • Debugging - exceptions are a type of bug; trace tables help find them
  • File Processing - file I/O heavily uses exception handling

Where this leads:

  • Debugging - strategies for finding and fixing errors