All subjects · Computer Science · WCP02 Practical Programming and Problem-solving
Exception handling with try and except
Edexcel IAL Computer Science · WCP02 Practical Programming and Problem-solving
A runtime error (exception) normally crashes a program. Exception handling catches it so the program can respond sensibly.
try and except (spec 7.1.1)
Code that might fail goes in a try block. If an exception happens, Python jumps to a matching except block instead of crashing. Name the exception you expect; a bare except: catches everything, which can hide bugs.
for text in ["12", "twelve"]:
try:
n = int(text)
print("Number", n)
except ValueError:
print("Not a whole number:", text)Output:
Number 12
Not a whole number: twelveIn-built exceptions you must know
The Programming Language Subset lists these:
| Exception | Typical cause |
|---|---|
| ValueError | Right type, unsuitable value: int("abc") |
| TypeError | Wrong type for the operation: "5" + 1 |
| ZeroDivisionError | Dividing by zero: 7 / 0 or 7 % 0 |
| IndexError | Index outside a list or string: [1, 2][5] |
| KeyError | Dictionary key that does not exist |
| NameError | Variable or function name not defined (often a typo) |
| FileNotFoundError | Opening a missing file for reading |
| AttributeError | Method that the type does not have: (5).upper() |
| UnboundLocalError | Local variable used before it is assigned in a function |
| EOFError | input() reaches the end of input |
| ArithmeticError, Exception | General parents: ArithmeticError covers ZeroDivisionError; Exception covers almost all |
Several except blocks
Python checks except blocks in order and runs the first one that matches. Put specific exceptions before general ones such as Exception.
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "cannot divide by zero"
except TypeError:
return "numbers only"
print(safe_divide(9, 3))
print(safe_divide(9, 0))
print(safe_divide(9, "3"))Output:
3.0
cannot divide by zero
numbers onlyRobust input
Combine a while loop with try/except to keep asking until the user types a valid number:
valid = False
while not valid:
try:
qty = int(input("Quantity: "))
valid = True
except ValueError:
print("Please type a whole number")Worked example
Which exception does each line raise? (a) [10, 20, 30][3] (b) {"a": 1}["b"] (c) int("3.5")
- (a) index 3 does not exist in a 3-item list: IndexError
- (b) the key "b" is missing: KeyError
- (c) "3.5" is a string but not a valid int: ValueError
Answer: IndexError, KeyError, ValueError
Check yourself
- Which exception is raised when this code runs?
```python
scores = [4, 8, 15]
print(scores[3])
```
- KeyError
- IndexError
- ValueError
- TypeError
Show answer
IndexError. Indexes run 0 to 2, so scores[3] raises IndexError.
- Which exception is raised when this code runs?
```python
total = 5
print(totl)
```
- ValueError
- KeyError
- SyntaxError
- NameError
Show answer
NameError. totl was never assigned, so Python raises NameError. Typos in identifiers usually cause this.
- Which exception is raised when this code runs?
```python
count = 0
def add_one():
count = count + 1
add_one()
```
- NameError
- UnboundLocalError
- TypeError
- IndexError
Show answer
UnboundLocalError. Assigning to count inside the function makes it local, but it is read before it has a local value, so Python raises UnboundLocalError.
- What is displayed when this code runs? Type each line of output in order, separated by spaces.
```python
try:
x = 10 / 0
print("A")
except ZeroDivisionError:
print("B")
print("C")
```
Show answer
B C. The division fails, so print("A") is skipped, the except block prints B, then the program continues with C: B, then C.
- What is displayed when this code runs?
```python
try:
value = int("4x")
except ZeroDivisionError:
print("zero")
except ValueError:
print("value")
except Exception:
print("other")
```
Show answer
value. int("4x") raises ValueError; the first matching except is the ValueError one, so value is displayed.
- What is displayed when this code runs?
```python
try:
n = int("42")
print(n + 1)
except ValueError:
print("bad")
```
Show answer
43. No exception happens, so the except block is skipped and 43 is displayed.
- This program should display 'missing' when the key is not in the dictionary. Which line completes it?
```python
stock = {"pen": 4, "ruler": 2}
try:
print(stock["glue"])
__________
print("missing")
```
- `except KeyError:`
- `except IndexError:`
- `except ValueError:`
- `except NameError:`
Show answer
`except KeyError:`. Looking up a missing dictionary key raises KeyError.
Sources
- Pearson Edexcel International Advanced Subsidiary/Advanced Level in Computer Science specification (XCP01/YCP01), first teaching 2026
- Pearson IAL Computer Science Unit 2 Programming Language Subset (PLS), Python 3
- Pearson IAL Computer Science IAS sample assessment materials (Unit 2 paper and mark scheme)
Last updated 8 November 2026. Spotted a mistake? Tell us.