You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers exception handling for the OCR A-Level Computer Science (H446) specification. Exception handling allows programs to detect and respond to runtime errors gracefully, rather than crashing unexpectedly.
An exception is a runtime event that disrupts the normal flow of program execution. Exceptions occur when something goes wrong during execution -- for example, dividing by zero, accessing a missing file, or providing invalid input.
| Term | Definition |
|---|---|
| Exception | A runtime error that disrupts normal program flow. |
| Throwing/raising | Creating an exception to signal an error. |
| Catching/handling | Detecting an exception and executing recovery code. |
| Stack trace | The sequence of function calls that led to the exception. |
| Exception (Python) | Cause |
|---|---|
ValueError | Invalid value (e.g., int("hello")) |
TypeError | Wrong data type (e.g., "text" + 5) |
ZeroDivisionError | Division by zero |
IndexError | List index out of range |
KeyError | Dictionary key not found |
FileNotFoundError | File does not exist |
PermissionError | Insufficient permissions |
AttributeError | Object does not have the attribute/method |
NameError | Variable not defined |
OverflowError | Numeric result too large |
The try/catch/finally structure (called try/except/finally in Python) is the primary mechanism for handling exceptions.
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code that runs if the specific exception occurs
print("Error: Cannot divide by zero")
finally:
# Code that ALWAYS runs, whether or not an exception occurred
print("This always executes")
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("Error: Please enter a valid integer")
except ZeroDivisionError:
print("Error: Cannot divide by zero")
except Exception as e:
print(f"Unexpected error: {e}")
The else block runs only if no exception was raised:
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input")
else:
print(f"You entered: {number}") # Only runs if no exception
finally:
print("Done") # Always runs
try block
|
+-- No exception --> else block --> finally block
|
+-- Exception raised --> matching except block --> finally block
Exam Tip: The
finallyblock always executes, even if there is areturnstatement in the try or except block. This makes it ideal for cleanup operations like closing files or database connections.
TRY
number = USERINPUT
number = INT(number)
result = 100 / number
OUTPUT result
EXCEPT ValueError
OUTPUT "Please enter a valid number"
EXCEPT ZeroDivisionError
OUTPUT "Cannot divide by zero"
ENDTRY
You can raise exceptions deliberately to signal that something has gone wrong.
def set_age(age: int):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age cannot exceed 150")
return age
try:
set_age(-5)
except ValueError as e:
print(f"Error: {e}") # Error: Age cannot be negative
You can create your own exception classes by inheriting from the built-in Exception class:
class InsufficientFundsError(Exception):
def __init__(self, balance: float, amount: float):
self.balance = balance
self.amount = amount
super().__init__(
f"Cannot withdraw {amount}: only {balance} available"
)
class BankAccount:
def __init__(self, balance: float):
self.__balance = balance
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.