An exception is a runtime error — a problem that occurs while a program is running, not while it is being written. Python's try/except block lets a program catch an exception before it crashes, handle it gracefully, and carry on. This is a key defensive-programming technique examined at GCSE level.
What is a runtime error and why does it cause a crash?
A runtime error occurs when code is syntactically correct (it runs) but encounters something unexpected during execution — dividing by zero, converting a letter to an integer, or accessing a list index that does not exist. Without any exception handling, Python stops immediately and prints a traceback, which is the crash report showing exactly where things went wrong.
Enter a number: hello
Traceback (most recent call last):
File "program.py", line 1, in <module>
number = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: 'hello'
The user sees a wall of technical text. A well-written program catches this and displays a friendly message instead.
What are the most common exceptions in Python?
| Exception | When it occurs | Example trigger |
|---|---|---|
ValueError |
Correct type, wrong value | int("hello") |
TypeError |
Wrong type entirely | "5" + 5 |
ZeroDivisionError |
Dividing by zero | 10 / 0 |
IndexError |
List index out of range | my_list[10] when list has 3 items |
FileNotFoundError |
File does not exist | open("missing.txt") |
KeyError |
Dictionary key not found | my_dict["age"] when key absent |
At GCSE, ValueError, ZeroDivisionError, and IndexError appear most frequently in exam questions.
How do you write a basic try/except block?
The structure is straightforward:
try:
# Code that might cause an error
age = int(input("Enter your age: "))
print("You are", age, "years old.")
except ValueError:
print("Please enter a whole number.")
How it works:
- Python runs the code inside
try. - If a
ValueErroroccurs (e.g. the user types "twenty"), Python jumps immediately to theexcept ValueErrorblock. - The
exceptblock runs and Python continues with the rest of the program. - If no exception occurs, the
exceptblock is skipped entirely.
How do you handle multiple exception types?
You can catch different exceptions in separate except clauses:
try:
number = int(input("Enter a number: "))
result = 100 / number
print("100 divided by", number, "is", result)
except ValueError:
print("That was not a valid number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
Python checks each except clause in order and runs the first one that matches the exception raised. This is analogous to an if/elif chain.
What are the else and finally clauses?
Two optional clauses extend the try/except block:
else— runs only if no exception was raised insidetry. Useful for code that should only run on success.finally— runs always, whether an exception occurred or not. Used for clean-up actions such as closing a file.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid input — not a number.")
else:
print("Age accepted:", age)
finally:
print("Thank you for using this program.")
Walkthrough — user enters "25":
| Step | What happens |
|---|---|
try block |
int("25") succeeds; age = 25 |
except ValueError |
Skipped — no exception occurred |
else block |
Runs: prints "Age accepted: 25" |
finally block |
Always runs: prints "Thank you..." |
Walkthrough — user enters "hello":
| Step | What happens |
|---|---|
try block |
int("hello") raises ValueError |
except ValueError |
Runs: prints "Invalid input — not a number." |
else block |
Skipped — an exception did occur |
finally block |
Always runs: prints "Thank you..." |
How do you use exception handling inside a validation loop?
Combining a while loop with try/except creates a robust input-validation pattern that keeps asking until the user provides valid data:
while True:
try:
score = int(input("Enter your score (0–100): "))
if score < 0 or score > 100:
print("Score must be between 0 and 100.")
else:
break # Valid — exit the loop
except ValueError:
print("Please enter a whole number.")
print("Score recorded:", score)
This handles two distinct problems: a non-integer input (caught by except ValueError) and an out-of-range integer (caught by the if check). Separating concerns in this way is a hallmark of well-structured defensive programming.
Frequently asked questions
What is the difference between a syntax error and an exception?
A syntax error is detected by Python before the program runs — it means the code violates Python's grammar (e.g. a missing colon after if, or unmatched brackets). Python refuses to start. An exception is detected during execution — the code is grammatically correct, but something unexpected happens at runtime (e.g. dividing by zero). try/except handles exceptions; syntax errors must be fixed in the code before the program can run at all.
Does exception handling appear in the GCSE exam?
Yes. AQA GCSE Computer Science papers include questions on exception handling as part of defensive programming. You may be asked to explain what a try/except block does, to identify which exception type a given error produces, or to write a short program that catches a ValueError when converting user input. Understanding the flow of execution (which block runs when) is the key skill being tested.
What happens if you do not specify an exception type in except?
Writing except: without an exception name catches every possible exception, including ones you may not have anticipated. This is generally considered bad practice because it can hide bugs — you might silently swallow a MemoryError or KeyboardInterrupt that you actually want to know about. At GCSE, always name the specific exception type you expect (e.g. except ValueError) to show that you understand precisely what error could occur.
Can you raise your own exceptions in Python?
Yes. The raise keyword lets you deliberately trigger an exception when a condition is not met:
age = int(input("Enter age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
This is useful in functions that need to signal an error to the caller. At GCSE level, you are unlikely to be asked to write raise yourself, but you may encounter it when reading code in exam questions.
For Socratic GCSE Computer Science tutoring on Python programming, exception handling, and defensive design, visit aitutors.me.