CIE AS & A Level Computer Science, section 20.2 (File processing and exception handling)
What an exception is
An exception is an error that occurs while a program is running (a run-time error), such as dividing by zero, a missing file, or invalid input. Without handling, the program crashes.
Why handle exceptions
- The program can recover or shut down safely instead of crashing.
- It can give the user a helpful message.
- It can close files and tidy up.
Structure
CIE's pseudocode guide has no exception-handling syntax: you write exception handling in program code (Paper 4). Most languages follow the same pattern, which can be outlined like this:
TRY
OPENFILE "data.txt" FOR READ
READFILE "data.txt", Line
EXCEPT
OUTPUT "File could not be read"
FINALLY
CLOSEFILE "data.txt"
ENDTRY
- TRY: the code that might cause the exception.
- EXCEPT: what to do if an exception happens.
- FINALLY: code that always runs, such as closing a file.
Python
def read_number():
try:
text = input("Enter a number: ")
value = int(text)
return 100 / value
except ValueError:
print("That was not a whole number")
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Finished")
def open_file(name):
try:
with open(name) as f:
return f.read()
except FileNotFoundError:
return "File not found"
print(open_file("missing.txt")) # File not found
Handling input errors in a loop
def get_age():
while True:
try:
age = int(input("Age: "))
if 0 <= age <= 120:
return age
except ValueError:
pass
print("Please enter a valid age")
Good practice
- Catch the specific exception, rather than every error.
- Do not hide errors silently.
- Use exception handling for unusual events, and validation for expected bad input.
Common mistake: putting too much code in the TRY block, or catching every error and ignoring it. Also, FINALLY runs whether or not an exception happens, so it is the right place to close a file.
Exam tip: name the error that could occur, and show the TRY, EXCEPT (with what the program does) and FINALLY parts. Say why the exception handling is useful: the program does not crash.
Check yourself
What is an exception?
An error that occurs while a program is running, which would normally stop it.
When does the FINALLY part run?
Always, whether or not an exception occurred.
Give an example of an exception that could be handled.
Dividing by zero, or trying to open a file that does not exist.