An exception is an event that occurs during program execution and interrupts the normal sequential flow of statements. It is raised when the runtime detects an error condition that the program has not explicitly anticipated – for example, trying to open a non‑existent file, dividing by zero, or accessing an array outside its bounds.
BaseException ├─ Exception │ ├─ IOError │ │ ├─ FileNotFoundError │ │ └─ PermissionError │ └─ ValueError │ └─ UnicodeDecodeError └─ SystemExit, KeyboardInterrupt, …
More specific exceptions inherit from broader ones. Catching a parent class (e.g., Exception) also catches all its subclasses, but this is usually discouraged because it hides the precise cause of the error.
catch/except clause is found.finally or language‑specific clean‑up code in each frame.raise (Python), throw (Java/VB) to let a higher level decide what to do.throws clause and either caught or re‑thrown by the caller (e.g., IOException).RuntimeException and need not be declared (e.g., NullPointerException, ArithmeticException).Exception (runtime) and COMException (system‑level).| Exception Type | Typical Cause | Common Handling Strategy |
|---|---|---|
| FileNotFoundError / FileNotFoundException | Attempt to open a file whose pathname does not exist. | Prompt for an alternative name, create the file, or abort with a clear message. |
| IOError / IOException | Read/write operation fails (disk error, network drop, unexpected EOF). | Retry, verify file integrity, or terminate gracefully. |
| PermissionError / SecurityException | Lack of required read/write privileges. | Inform the user, request elevated rights, or choose a different directory. |
| EOFError / EndOfStreamException | Attempt to read past the end of a file/stream. | Stop reading, possibly process partial data, and close the stream. |
| Concept | Python | Java | Visual Basic |
|---|---|---|---|
| Try block | try: |
try { |
Try |
| Catch / Except clause(s) | except FileNotFoundError as e: |
catch (FileNotFoundException e) { … } |
Catch ex As IOException |
| Multiple specific catches | Multiple except blocks (ordered from specific to general). |
Multiple catch blocks; the first matching type is executed. |
Multiple Catch blocks; same rule as Java. |
| Else / Finally | else: (runs if no exception) finally: |
finally { … } |
Finally |
| Automatic resource management | Context manager: with open(... ) as f: |
Try‑with‑resources: try (BufferedReader br = …) { … } |
Using stream As New FileStream(...) |
| Raising / Throwing | raise ValueError('msg') |
throw new IllegalArgumentException("msg") |
Throw New ArgumentException("msg") |
def process_file(path):
try:
# Automatic closing with a context manager – no explicit finally needed
with open(path, 'r', encoding='utf-8') as file:
for line in file:
process(line) # user‑defined processing routine
except FileNotFoundError:
print(f'Error: The file "{path}" was not found.')
except PermissionError:
print(f'Error: Insufficient permissions to read "{path}".')
except UnicodeDecodeError:
print('Error: File encoding is not UTF‑8.')
except Exception as e: # catch‑all for unexpected problems
print('An unexpected error occurred:', e)
raise # re‑throw after logging
else:
print('File processed successfully.')
Key points illustrated:
except clauses are ordered from most specific to most general.else block runs only when no exception is raised.with statement guarantees the file is closed (resource‑release construct).raise preserves the original traceback for higher‑level handling.
public void readFile(String path) {
try (BufferedReader br = Files.newBufferedReader(
Paths.get(path), StandardCharsets.UTF_8)) {
String line;
while ((line = br.readLine()) != null) {
process(line); // user‑defined processing routine
}
} catch (NoSuchFileException e) {
System.err.println("Error: File not found – " + path);
} catch (AccessDeniedException e) {
System.err.println("Error: No permission to read – " + path);
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
throw new UncheckedIOException(e); // re‑throw as unchecked
} finally {
System.out.println("Attempt to read completed."); // optional, resources already closed
}
}
This example demonstrates:
IOException) that must be caught or declared.BufferedReader via the try‑with‑resources statement.| Aspect | Normal Flow | Exception Flow |
|---|---|---|
| Entry point | Control reaches the statement directly. | An error is raised before the statement completes. |
| Control transfer | Sequential execution of the next statement. | Runtime jumps to the nearest matching except/catch block; stack frames unwind. |
| Resource management | Resources released at the end of the block (or rely on garbage collection). | finally or language‑specific constructs (e.g., with, try‑with‑resources) guarantee release. |
| Propagation | Not applicable. | If no local handler matches, the exception propagates up the call stack. |
When built‑in types are insufficiently descriptive, you can define your own exception class. The class should inherit from the language’s base exception type.
| Language | Definition | Raising the Exception |
|---|---|---|
| Python | class InvalidRecordError(Exception):
"""Raised when a data record fails validation."""
pass |
if not validate(record):
raise InvalidRecordError('Record format is incorrect') |
| Java | public class InvalidRecordException extends Exception {
public InvalidRecordException(String message) {
super(message);
}
} |
if (!validate(record)) {
throw new InvalidRecordException("Record format is incorrect");
} |
| Visual Basic | Public Class InvalidRecordException
Inherits Exception
Public Sub New(msg As String)
MyBase.New(msg)
End Sub
End Class |
If Not Validate(record) Then
Throw New InvalidRecordException("Record format is incorrect")
End If |
with, try‑with‑resources, Using).FileNotFoundError raised in process_file(), bubbling up through main(), and finally caught by a top‑level handler.Exception handling transforms unpredictable runtime errors into controlled, recoverable events. By mastering the hierarchy, propagation, and language‑specific constructs (try‑catch‑finally, context managers, try‑with‑resources), and by integrating this knowledge with the broader Cambridge AS/A‑Level syllabus—information representation, networking, hardware, system software, security, ethics, databases, and algorithm design—students can write robust, maintainable programs that meet both technical and real‑world requirements.
Create an account or Login to take a Quiz
Log in to suggest improvements to this note.
Your generous donation helps us continue providing free Cambridge IGCSE & A-Level resources, past papers, syllabus notes, revision questions, and high-quality online tutoring to students across Kenya.