Exception Handling
IB Syllabus: B2.1.3 — Construct code using exception handling: try, catch, finally.
Table of Contents
- Key Concepts
- Worked Examples
- Quick Code Check
- Trace Exercise
- Code Completion
- Spot the Bug
- Output Prediction
- Practice Exercises
- GitHub Classroom
- Connections
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
}
| 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 |
The
finallyblock is optional, but when present it always executes — whether thetrysucceeded or thecatchran. 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 |
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.");
}
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.");
}
Key points:
- You can have multiple catch blocks for different exception types
- The
finallyblock prints"Program complete."regardless of what happened - If the user enters
0, theArithmeticExceptioncatch runs, thenfinallyruns
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());
}
Output:
Error: cannot divide by zero.
Message: / by zero
e.getMessage()returns a short description of what went wrong. This is useful for debugging.
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);
After an
InputMismatchException, the invalid input remains in the Scanner buffer. You must callinput.nextLine()to clear it before the next iteration, otherwise the loop runs forever.
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
}
Catch specific exceptions, not
Exception. Catching everything makes bugs invisible and programs harder to debug.
Quick Code 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");
| Line | Does 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?
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 Bug
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.
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?
Output Prediction
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");
}
Start
Caught
FinallyPractice Exercises
Core
-
Safe division — Read two integers. Use try-catch to handle division by zero and print an error message instead of crashing.
-
Safe input — Read an integer using Scanner. If the user enters non-numeric text, catch the
InputMismatchExceptionand print a friendly message. -
With finally — Modify exercise 1 to include a
finallyblock that prints “Calculation attempt complete.”
Extension
-
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. -
Array bounds — Create an array of 5 elements. Ask the user for an index and try to access that element. Catch
ArrayIndexOutOfBoundsExceptionif the index is invalid.
Challenge
- 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
Connections
Prerequisites:
- Variables & Data Types — understanding types and operations that can fail
- Selection — if/else logic used alongside try-catch
Related Topics:
- Debugging — exceptions are a type of bug; trace tables help find them
- File Processing — file I/O heavily uses exception handling
What’s Next:
- Debugging — strategies for finding and fixing errors