A Level · Topic 20.2
A-Level Computer Science 9618 / Topic 20 / A2

Expect the unexpected.

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.

The key idea

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.

What happens when an exception is raised inside a try block try block exception raised rest of the program except / catch handler statements that might fail e.g. file not found, divide by 0 continues normally message, retry or safe default no error:handler skipped error control jumpsto the handler Without a handler the exception is unhandled and the program crashes with a run-time error
Fig. 1: if nothing goes wrong the handler is skipped; if an exception is raised, control jumps to the handler
Section 01

What is an exception?

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.

CauseExamplePython exception
File missing or lockedopening Scores.txt for reading when it does not existFileNotFoundError, PermissionError
Invalid conversionint("seven") when the user types a wordValueError
Arithmeticdividing by a count that turns out to be 0ZeroDivisionError
Out of rangeaccessing element 11 of a 10-element listIndexError
Hardware or networka storage device removed, a connection lost, memory fullOSError, ConnectionError, MemoryError
Examiner trap

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.

Section 02

Writing exception-handling code.

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")
LanguageStructure
Pythontry: ... except ValueError: ... finally: ...
Javatry { ... } catch (NumberFormatException e) { ... } finally { ... }
VB.NETTry ... Catch ex As Exception ... Finally ... End Try
Worked example Trace the handler
Totals.txt holds four lines: 12, 7, abc and 5. What does read_total("Totals.txt") output and return? What happens if the file does not exist?
  1. The file opens, so the first except block is skipped and total starts at 0.
  2. Line 12: int succeeds, total = 12. Line 7: total = 19.
  3. Line abc: int("abc") raises ValueError. The rest of the try block (the addition) is skipped and the handler prints Skipped a line that is not a whole number: abc. The loop then carries on.
  4. Line 5: total = 24. The file is closed and 24 is returned.
  5. If the file does not exist, open raises FileNotFoundError, the handler prints Cannot find Totals.txt and the function returns -1 instead of crashing.
Answer: It outputs one message about abc and returns 24. Without the inner handler, the bad line would have crashed the whole program and the valid numbers would have been lost.
Your turn
In Python, a try block contains 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?
Examiner trap

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.

Stage 1 · Learn

Check what the sim just showed you

Four quick checks. Each correct answer earns XP and records this skill on your profile.

Quick check+10 XP

What is an exception?

Quick check+10 XP

When an exception is raised inside a try block, what happens next?

Quick check+10 XP

Which situation is most suited to exception handling?

Quick check+10 XP

What is a finally block used for?

Section 03

When to use exception handling.

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.

SituationBetter approachReason
Opening a file that another user may have deletedexception handlingthe file could vanish between any check and the open, so only the attempt itself is reliable
Reading from a network or external deviceexception handlingthe connection or device can fail at any moment, outside the program's control
Converting typed input to a numberexception 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 100validation 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 arrayfix the logic errorcatching the exception would hide a bug that should be corrected
Worked example Choose and justify
A weather station program reads a value from a temperature sensor every minute, calculates the average of the last 60 readings and stores it in a file. Identify two places where exception handling is appropriate and say what each handler should do.
  1. Reading the sensor: the device may be disconnected or fail to respond. The handler could log the fault and skip that reading so the program keeps running.
  2. Writing to the file: the storage may be full or unavailable. The handler could display or log a warning and keep the average in memory to retry later, rather than crashing.
  3. Calculating the average: if every reading failed the count would be 0, so a division by zero is possible. An IF check that the count is greater than 0 is the clearer solution here, because the condition is predictable.
Answer: Sensor reads and file writes need exception handling because they depend on hardware outside the program's control; the possible division by zero is better prevented with an IF check.
Examiner trap

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

Stage 2 · Exam

Exam-style questions

Unlocks once the four checks above are done. Worth more XP, written to A Level Paper 3 and Paper 4 standard.

Finish the four checks above to unlock the exam questions
Exam style+20 XP

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?

Exam style+20 XP

Which is the best explanation of why exception handling is important?

Exam style+20 XP

A program divides a total by a count that the program itself has just checked is greater than 0. Which statement is correct?

Exam style+20 XP

Which VB.NET structure handles an exception?

Skill unlocked

Exception handling, caught.

This skill is now recorded on your profile. Keep the chain going.

-Rank -Level -Score -Topics
Go deeper · practice
Six original Cambridge-style questions
What an exception is, why handling exceptions matters, writing try / except / finally code, and when exception handling is appropriate.