Pro Content

Upgrade to access exception handling, defensive programming, and all Cambridge 9618 lessons.

Upgrade to Pro →
← Back to Dashboard
📗 Paper 4 · 4.2 Further OOP
4.2.3 Exception Handling & Robustness
Cambridge 9618 · International A Level Computer Science · ~16 min read
Notes
Video
Slides
Quiz
Worksheet

What is an Exception?

An exception is an abnormal event or error that occurs during the execution of a program — at runtime (not at compile time). If not handled, an exception causes the program to terminate abruptly with an error message.

Exceptions differ from syntax errors (caught at compile time) and logic errors (wrong output but no crash). Exceptions are runtime errors that the program can potentially detect and recover from.

Examples: dividing by zero, accessing an index that doesn't exist, reading a file that doesn't exist, converting "hello" to an integer.

TRY–EXCEPT–FINALLY (Try-Catch-Finally)

Exception handling uses a structured block to separate normal code from error-handling code. Cambridge 9618 pseudocode uses TRY…EXCEPT…FINALLY.

TRY block
Code that might throw an exception. Runs normally if no exception occurs. If an exception is thrown, execution immediately jumps to EXCEPT — remaining TRY code is skipped.
EXCEPT block
Runs only if an exception was thrown in TRY. Handles the error — shows a message, logs the error, provides a default value. May specify the exception type to catch specific errors.
FINALLY block
ALWAYS runs — whether an exception occurred or not. Used for cleanup code: closing files, releasing resources, closing database connections. Cannot be skipped.

Cambridge pseudocode syntax

TRY
  xUSERINPUT()
  result100 / x    // might throw DivisionByZero
  OUTPUT "Result: " + result
EXCEPT DivisionByZeroException
  OUTPUT "Error: cannot divide by zero"
EXCEPT Exception    // catches any other exception
  OUTPUT "An unexpected error occurred"
FINALLY
  OUTPUT "Calculation attempt complete"    // always runs
ENDTRY

Common Exception Types

DivisionByZeroException
Thrown when a program attempts to divide a number by zero.
result ← 10 / 0
NullPointerException
Thrown when code tries to use an object reference that is NULL.
obj.method() when obj = NULL
IndexOutOfBoundsException
Thrown when accessing an array/list at an index that doesn't exist.
arr[10] when arr has 5 elements
IOException / FileNotFoundException
Thrown when a file operation fails — file not found, no permission, disk full.
OPENFILE "missing.txt"
ValueError / TypeMismatch
Thrown when converting incompatible types, e.g. converting "hello" to an integer.
INT("hello")
Custom Exceptions
User-defined exceptions that inherit from the base Exception class. Used for application-specific errors.
CLASS InsufficientFunds INHERITS Exception

Throwing Exceptions (THROW)

Code can throw (raise) its own exceptions using the THROW keyword. This is useful when a method detects an invalid condition and wants to signal the caller.

CLASS BankAccount
  PUBLIC PROCEDURE withdraw(amount : REAL)
    IF amount > balance THEN
      THROW InsufficientFundsException("Balance too low")
    ENDIF
    balancebalanceamount
  ENDPROCEDURE
ENDCLASS

// Calling code handles the exception
TRY
  account.withdraw(500.00)
EXCEPT InsufficientFundsException AS e
  OUTPUT "Transaction failed: " + e.getMessage()
ENDTRY

Exception Propagation

If an exception is thrown inside a method and that method has no EXCEPT block to handle it, the exception propagates up the call stack — it passes to the calling method. This continues until it is caught or reaches the top (main program), where it causes the program to crash.

main()→ callsprocessOrder()
processOrder()→ callsreadFile()
readFile()throwsIOException
↑ propagates back ↑ (if readFile has no EXCEPT, IOException bubbles up to processOrder, then to main)
main() catches IOException → shows user-friendly message

Defensive Programming

Defensive programming means writing code that continues to work correctly even when given unexpected, incorrect, or extreme inputs. It is a proactive approach — preventing errors before they occur, rather than just catching them after.

❌ Non-defensive
FUNCTION divide(a, b : REAL)
  RETURN a / b // crashes if b=0
ENDFUNCTION
✅ Defensive
FUNCTION divide(a, b : REAL)
  IF b = 0 THEN
    THROW DivisionByZeroException
  ENDIF
  RETURN a / b
ENDFUNCTION

Robustness

A robust program continues to work (or fails gracefully with useful messages) even under unexpected conditions. Robustness techniques include:

  • Input validation — check inputs are in valid range before processing
  • Exception handling — catch and recover from runtime errors
  • Precondition checking — assert that required conditions are met before executing
  • Default/fallback values — use sensible defaults when input is invalid
  • Logging — record errors for later diagnosis without crashing
Cambridge 9618 exam tip: Know the three parts: TRY (risky code), EXCEPT (error handler), FINALLY (always runs — cleanup). Be able to explain WHY FINALLY is needed (e.g. if an exception occurs during file processing, FINALLY closes the file even if an exception was thrown). Know what "exception propagation" means — if a method doesn't handle an exception, it passes to the calling method. Distinguish exception handling (reactive — catches errors when they occur) from defensive programming (proactive — validates input before errors can occur). Custom exceptions: subclass the base Exception class; useful for domain-specific errors like InsufficientFundsException or InvalidAgeException.
⚠️ Common Mistakes
  • Saying FINALLY only runs if an exception occurred — FINALLY ALWAYS runs, regardless of whether an exception was thrown or caught. That's its entire purpose — guaranteed cleanup.
  • Catching all exceptions with a generic Exception catch without specific ones first — always put specific exception catches before the generic Exception catch. A generic Exception catch-all should be last as a fallback, not first.
  • Confusing THROW with EXCEPT — THROW raises/triggers an exception from inside a method. EXCEPT (or CATCH) handles an exception that has been thrown. THROW sends it; EXCEPT receives it.
  • Thinking exception handling eliminates the need for validation — it doesn't. Exception handling is for exceptional cases; normal input validation (checking range, type) should still prevent invalid data from reaching code. Defensive programming uses both.
  • Confusing runtime exceptions with compile-time errors — exceptions are runtime events; syntax errors are caught at compile time. An exception can only occur during program execution, not before it starts.
  • Leaving resources open if an exception occurs — always close files/connections in FINALLY, not after the TRY block. If an exception occurs in TRY, code after TRY doesn't run — only FINALLY is guaranteed to run.
✅ Notes completed!
Video coming soon
Click slide or press arrow keys to navigate

Worksheet — 4.2.3 Exception Handling

8 questions · Cambridge 9618 standard

Q1Explain the purpose of each of the three parts of a TRY-EXCEPT-FINALLY block.[3]
✅ Mark scheme
TRY: contains the code that might throw an exception — runs normally if no exception occurs; if an exception is thrown, execution jumps immediately to the relevant EXCEPT block [1]; EXCEPT: runs only when a matching exception is thrown in the TRY block; handles the error — e.g. displays an error message, provides a default value, logs the error [1]; FINALLY: always runs regardless of whether an exception was thrown or caught; used for cleanup operations such as closing files, releasing resources, or closing database connections [1].
Q2Write pseudocode that reads an integer from the user, divides 100 by it, and outputs the result. Include exception handling for division by zero and any other exception.[5]
✅ Mark scheme
TRY keyword [1]; INPUT or USERINPUT to read an integer [1]; result ← 100 / divisor (or equivalent) [1]; EXCEPT DivisionByZeroException handling — appropriate output [1]; EXCEPT Exception or general catch — appropriate output [1]. FINALLY optional but accept. Correct ENDTRY. Award marks for correct structure even if keywords differ slightly.
Q3Explain what "exception propagation" means. Use an example with three levels of method calls to illustrate.[3]
✅ Mark scheme
Exception propagation: if a method throws an exception and does not handle it (has no matching EXCEPT), the exception passes to the calling method; this continues up the call stack until the exception is caught or reaches the top level [1]; example: main() calls loadData() which calls readFile(); readFile() throws IOException but has no EXCEPT [1]; IOException propagates up to loadData() — if loadData() has no EXCEPT, it propagates further to main() — main() catches it and shows an error message [1].
Q4Explain the difference between exception handling and defensive programming. Give one example technique from each approach.[4]
✅ Mark scheme
Exception handling is reactive — it responds to errors that have already occurred at runtime, using TRY-EXCEPT to catch and recover from exceptions [1]; example: wrapping a file read operation in TRY-EXCEPT to handle FileNotFoundException if the file is missing [1]; defensive programming is proactive — it anticipates potential problems and prevents them before they occur, using input validation and precondition checks [1]; example: checking that a divisor is non-zero BEFORE performing division, or checking that an array index is within bounds BEFORE accessing the element [1].
Q5Describe how to create a custom exception class InsufficientFundsException in pseudocode. When should a programmer use a custom exception rather than a built-in one?[3]
✅ Mark scheme
Custom exception: CLASS InsufficientFundsException INHERITS Exception — the custom class inherits from the built-in Exception base class [1]; it can add its own attributes (e.g. amount : REAL — the amount that was lacking) and its own constructor; when thrown: THROW InsufficientFundsException("Balance too low") [1]; use a custom exception when: a built-in exception doesn't clearly describe the domain-specific error; you want to catch only this specific error type in calling code without catching other unrelated exceptions; you need to carry additional information specific to the error (e.g. the account balance at the time of the error) [1].
Q6A program opens a file, processes it, then closes it. Explain why it is important to close the file in the FINALLY block rather than at the end of the TRY block.[3]
✅ Mark scheme
If an exception occurs during file processing inside the TRY block, execution immediately jumps to the EXCEPT block — the remaining code in TRY does not run [1]; this means if the file close statement is at the END of the TRY block, it will be SKIPPED if an exception is thrown; the file would remain open — wasting resources, potentially corrupting data, or preventing other processes from accessing it [1]; FINALLY always runs regardless of whether an exception occurred — placing the file close in FINALLY guarantees it runs in all cases: successful completion AND exception scenarios [1].
Q7Write pseudocode for a procedure ReadFile that opens a file "scores.dat", reads and outputs each line using a WHILE NOT EOF loop, then closes the file. The procedure should use a TRY-EXCEPT block to handle a FileNotFoundException, outputting an appropriate error message if caught.[6]
✅ Mark scheme
Award 1 mark each for: TRY keyword present [1]; OPENFILE "scores.dat" FOR READ inside TRY [1]; WHILE NOT EOF("scores.dat") loop reading and outputting each line [1]; CLOSEFILE "scores.dat" after loop [1]; EXCEPT clause catching FileNotFoundException [1]; meaningful error message output in EXCEPT block [1].
Q8Explain the difference between a FINALLY block and an EXCEPT block in exception handling. Give one scenario where a FINALLY block is essential even if no exception is raised.[4]
✅ Mark scheme
EXCEPT executes only when an exception is raised / handles the error [1]; FINALLY executes always, whether or not an exception occurred [1]; Scenario: closing a file — if the file must always be closed regardless of whether an error occurs, FINALLY ensures the CLOSEFILE is always executed [1]; without FINALLY, a file opened before an exception would remain open, wasting resources [1].
Topic Quiz
Question 1 of 10
You scored
out of 10
Card 1 of 8
Click to reveal definition
🎉
All cards reviewed!
TermDefinition
🎯

Mini Test — 4.2.3 Exception Handling

10 questions · 10 marks · 10 minutes

← 4.2.2 Design Patterns
70 of 82 · Cambridge 9618
4.2.4 File Handling →