AQA 7517, section 4.1.1.9
Things go wrong while programs run. A user types letters where a number is expected, a file is missing, or a calculation divides by zero. When this happens the program raises an exception, and unless something deals with it, the program stops with an error message.
Exception handling is the technique of detecting these errors as they happen and responding to them in a controlled way, so the program can recover or end tidily.
Why use exception handling?
- The program doesn't crash when something unexpected happens.
- You can give the user a useful message and let them try again.
- The program can clean up, for example closing a file.
- Error handling is separated from the main logic, so the normal path stays easy to read.
try and except
In Python, code that might fail goes inside a try block. If an exception occurs, Python jumps straight to the matching except block.
try:
age = int(input("Age: "))
print("Next year you will be", age + 1)
except ValueError:
print("Please enter a whole number.")
If the user types 17, the try block completes and the except block is skipped. If they type seventeen, int() raises a ValueError, the rest of the try block is skipped, and the message is printed instead.
Common exceptions
| Exception | Raised when |
|---|---|
ValueError |
A value has the right type but is unsuitable, such as int("abc") |
ZeroDivisionError |
Dividing by zero |
IndexError |
An index is outside a list, such as items[10] on a short list |
KeyError |
A dictionary key doesn't exist |
FileNotFoundError |
A file can't be found |
TypeError |
An operation is applied to the wrong type, such as "a" + 1 |
else and finally
else runs if no exception happened. finally runs whatever happens, so it is used for clean-up.
try:
f = open("scores.txt")
except FileNotFoundError:
print("File not found")
else:
print("File opened")
f.close()
finally:
print("Done")
Worked example
Task: keep asking for a number until the user gives a valid one, then divide 100 by it without crashing.
valid = False
while not valid:
try:
n = int(input("Enter a number: "))
result = 100 / n
valid = True
except ValueError:
print("That wasn't a whole number.")
except ZeroDivisionError:
print("You can't divide by zero.")
print("100 divided by", n, "is", result)
Trace it with the inputs abc, 0, 4:
abc:int("abc")raises aValueError, the message prints, andvalidis stillFalse, so the loop repeats.0:intworks, but100 / 0raises aZeroDivisionError, the second message prints, and the loop repeats.4: no exception,validbecomesTrue, the loop ends, and it prints25.0.
Each except names the specific problem, so the program can respond to each one differently.
Watch out: don't use a bare except: that catches everything and does nothing. It hides real bugs, which then become very hard to find. Catch the specific exceptions you expect.
Exam tip: exception handling is for unexpected events while the program runs. It is not the same as validating data with an if statement, although both help to make a program robust. Explain what could go wrong and what the handler does about it.
Check yourself
What is an exception?
An error that occurs while a program is running and which stops normal execution unless it is handled.
Give two reasons for using exception handling
Any two of: it stops the program crashing; it lets the program give a helpful message or recover; it lets the program clean up resources; it keeps the error-handling code separate from the main logic.
What does the code in a finally block do?
It runs whether or not an exception occurred, so it is used for clean-up such as closing a file.
Which exception would int("12.5") raise?
A ValueError, because "12.5" is not a valid whole number string.