Files go missing, users type letters where numbers belong and networks drop out. Learn what an exception is, why handling exceptions matters, how to write try and except (or catch) blocks in program code, and how to judge when exception handling is the right tool and when ordinary validation is better.
An exception is an unexpected event or error that happens while a program is running (a run-time error) and disrupts the normal flow of instructions, for example a file not found, division by zero, a failed type conversion or an array index out of range. If it is not handled, the program crashes. Exception handling places code that might fail in a try block; if an exception is raised (thrown), control jumps to a matching except / catch block, which can report the problem, retry or use a safe default, so the program can continue or end gracefully. An optional finally block runs either way, for tidying up such as closing files.
Syntax errors stop a program being translated; logic errors give wrong answers. Exceptions are different: the code is valid, but something goes wrong at run time, often because of something outside the program's control.
| Cause | Example | Python exception |
|---|---|---|
| File missing or locked | opening Scores.txt for reading when it does not exist | FileNotFoundError, PermissionError |
| Invalid conversion | int("seven") when the user types a word | ValueError |
| Arithmetic | dividing by a count that turns out to be 0 | ZeroDivisionError |
| Out of range | accessing element 11 of a 10-element list | IndexError |
| Hardware or network | a storage device removed, a connection lost, memory full | OSError, ConnectionError, MemoryError |
An exception is a run-time event. Exception handling cannot catch a syntax error (the program would not run at all) and does not fix a logic error that simply produces the wrong answer.
The 9618 pseudocode guide does not define any exception-handling statements, so you write this in your Paper 4 language. The structure is the same in all three: the risky code goes in the try block and the handler follows it.
def read_total(filename):
total = 0
try:
file = open(filename, "r")
except FileNotFoundError:
print("Cannot find", filename)
return -1
for line in file:
try:
total = total + int(line)
except ValueError:
print("Skipped a line that is not a whole number:", line.strip())
file.close()
return total
Asking again until the user types a valid whole number:
valid = False
while not valid:
try:
age = int(input("Enter your age: "))
valid = True
except ValueError:
print("Please enter a whole number")
| Language | Structure |
|---|---|
| Python | try: ... except ValueError: ... finally: ... |
| Java | try { ... } catch (NumberFormatException e) { ... } finally { ... } |
| VB.NET | Try ... Catch ex As Exception ... Finally ... End Try |
x = 10 / 0 and then print("A"). It has a handler except ZeroDivisionError: that prints B and a finally: block that prints C. After the whole structure, the program prints D. What is output?Put only the statements that might fail, and the ones that depend on them, inside the try block. Code after the failing statement in the try block is skipped, so a total updated after the risky conversion is safe, but one updated before it is not rolled back.
Four quick checks. Each correct answer earns XP and records this skill on your profile.
What is an exception?
When an exception is raised inside a try block, what happens next?
Which situation is most suited to exception handling?
What is a finally block used for?
Exception handling is not a replacement for careful programming. Use it where an error cannot reliably be prevented by a check in advance, usually because the cause is outside the program.
| Situation | Better approach | Reason |
|---|---|---|
| Opening a file that another user may have deleted | exception handling | the file could vanish between any check and the open, so only the attempt itself is reliable |
| Reading from a network or external device | exception handling | the connection or device can fail at any moment, outside the program's control |
| Converting typed input to a number | exception handling (or a format check) | the conversion fails for any non-numeric text; catching the exception lets the program ask again |
| A mark that must be from 0 to 100 | validation with IF (range check) | a predictable rule the program can test directly; out-of-range data does not cause an exception |
| A loop that runs one place past the end of an array | fix the logic error | catching the exception would hide a bug that should be corrected |
"Exception handling stops the program crashing" is only part of the answer. To earn the marks, say what the handler does: outputs a meaningful message, retries, uses a default value, saves data or closes files.
Unlocks once the four checks above are done. Worth more XP, written to A Level Paper 3 and Paper 4 standard.
In Python, x = int("4.5") is followed by print("A") in a try block, with except ValueError: print("B"). After the structure, print("C") runs. What is output?
Which is the best explanation of why exception handling is important?
A program divides a total by a count that the program itself has just checked is greater than 0. Which statement is correct?
Which VB.NET structure handles an exception?
This skill is now recorded on your profile. Keep the chain going.