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 x ← USERINPUT() result ← 100 / x// might throw DivisionByZero OUTPUT"Result: " + result EXCEPTDivisionByZeroException OUTPUT"Error: cannot divide by zero" EXCEPTException// 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.
CLASSBankAccount PUBLIC PROCEDUREwithdraw(amount : REAL) IFamount > balanceTHEN THROWInsufficientFundsException("Balance too low") ENDIF balance ← balance − amount ENDPROCEDURE ENDCLASS
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)
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!
Term
Definition
🎯
Mini Test — 4.2.3 Exception Handling
10 questions · 10 marks · 10 minutes
⏱ 10:00
Section A — Multiple Choice [5 marks]
Q1When does the FINALLY block execute in a TRY-EXCEPT-FINALLY structure?
Q2An exception is thrown in method C. Method C has no EXCEPT block. Method B called C; method A called B. Where will the exception be caught?
Q3Which exception is thrown when code attempts to access array element index 10 in an array that only has 5 elements?
Q4What keyword is used to raise/trigger an exception from inside a method?
Q5Which of the following is a correct description of defensive programming?
Section B — Short Answer [5 marks]
Q6Explain why custom exceptions are useful. Describe how to create one that inherits from the base Exception class.
Mark schemeCustom exceptions allow domain-specific, meaningful errors — e.g. InsufficientFundsException is much clearer than a generic RuntimeException [1]; allows callers to catch only that specific exception type rather than all exceptions — more precise error handling [1]; created with: CLASS InsufficientFundsException INHERITS Exception — the custom class inherits all base exception behaviour and can add its own attributes (message, amount) and constructor [1].
Q7A BankAccount withdraw method should not allow negative withdrawal amounts. Write pseudocode showing how to validate this using defensive programming (input check before processing).
Mark schemePROCEDURE withdraw(amount : REAL) [1]; IF amount <= 0 THEN THROW InvalidAmountException("Amount must be positive") ENDIF [1]; IF amount > balance THEN THROW InsufficientFundsException ENDIF; balance ← balance − amount [1]. Key: precondition checks BEFORE the main operation; THROW with appropriate exception type. Award marks for correct validation structure even if keywords differ slightly.
Q8What is a NullPointerException and when does it occur? Give a code example that would cause one.
Mark schemeA NullPointerException occurs when code attempts to call a method or access an attribute on an object reference that is NULL (has not been assigned an actual object) [1]; it occurs when a variable holds NULL instead of an object, but code treats it as if it holds a valid object [1]; example: DECLARE obj : MyClass (without assigning NEW MyClass()); then calling obj.doSomething() — since obj is NULL, trying to access any attribute or method causes NullPointerException [1].
Q9Explain the difference between a runtime exception and a compile-time syntax error. Give one example of each.
Mark schemeCompile-time syntax error: detected by the compiler BEFORE the program runs; the program cannot start if syntax errors exist; example: missing ENDFUNCTION, misspelled keyword, wrong bracket — the interpreter/compiler rejects the code [1]; runtime exception: occurs DURING program execution — the program compiles and starts successfully but encounters an unexpected condition during execution [1]; example: dividing by a user-inputted zero (valid syntax, but execution fails when zero is entered); accessing a missing file; calling a method on a NULL object [1].
Q10Describe what "robust" software means. Give three specific techniques a developer can use to make software more robust.
Mark schemeRobust software continues to operate correctly (or fails gracefully with meaningful error messages) even when given unexpected, invalid, or extreme inputs — it doesn't crash under unusual conditions [1]; techniques (any 3): input validation — check that all inputs are within expected range and type before processing [1]; exception handling — wrap potentially failing operations in TRY-EXCEPT to catch and recover from runtime errors [1]; precondition checking — verify required conditions are met before executing a method [1]; fallback/default values — use a safe default when invalid input is detected rather than crashing [1]; error logging — record errors to a log file for later diagnosis without terminating the program [1].