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.

Practise this in the app: instant marking and a fix for every mistake. Free, no email needed to start.

Practise this lesson

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: twelve

In-built exceptions you must know

The Programming Language Subset lists these:

ExceptionTypical cause
ValueErrorRight type, unsuitable value: int("abc")
TypeErrorWrong type for the operation: "5" + 1
ZeroDivisionErrorDividing by zero: 7 / 0 or 7 % 0
IndexErrorIndex outside a list or string: [1, 2][5]
KeyErrorDictionary key that does not exist
NameErrorVariable or function name not defined (often a typo)
FileNotFoundErrorOpening a missing file for reading
AttributeErrorMethod that the type does not have: (5).upper()
UnboundLocalErrorLocal variable used before it is assigned in a function
EOFErrorinput() reaches the end of input
ArithmeticError, ExceptionGeneral 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 only

Robust 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")

  1. (a) index 3 does not exist in a 3-item list: IndexError
  2. (b) the key "b" is missing: KeyError
  3. (c) "3.5" is a string but not a valid int: ValueError

Answer: IndexError, KeyError, ValueError

Key idea: Put risky code in try and handle named exceptions in except, specific before general; know ValueError, TypeError, ZeroDivisionError, IndexError, KeyError, NameError and FileNotFoundError.

Check yourself

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Practise with instant feedback

Sources

Last updated 8 November 2026. Spotted a mistake? Tell us.