Why Handle Errors?
Code crashes ruin user experience. Exception handling lets you catch errors and respond gracefully.
Basic try/except
try:
n = int(input("Enter a number: "))
print(10 / n)
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
Catching Any Exception
try:
risky_operation()
except Exception as e:
print(f"Something went wrong: {e}")
Warning: Avoid catching all exceptions blindly โ you hide bugs.
Multiple Exceptions
try:
result = do_something()
except (TypeError, ValueError) as e:
print(f"Bad input: {e}")
except IOError as e:
print(f"File problem: {e}")
try/except/else/finally
try:
f = open("data.txt")
except FileNotFoundError:
print("File not found")
else:
# runs if no exception
print("File opened")
f.close()
finally:
# ALWAYS runs (cleanup)
print("Done")
Common Built-In Exceptions
| Exception | When It Happens |
|---|---|
| ValueError | Wrong value type (e.g. int("abc")) |
| TypeError | Wrong type operation (e.g. "a"+1) |
| KeyError | Missing dictionary key |
| IndexError | List index out of range |
| FileNotFoundError | File doesn't exist |
| ZeroDivisionError | Dividing by zero |
| AttributeError | Missing attribute/method |
Raising Exceptions
def calculate_age(year):
if year > 2026:
raise ValueError("Year cannot be in the future")
return 2026 - year
try:
calculate_age(2030)
except ValueError as e:
print(f"Error: {e}")
Practical Input Validation
def get_positive_int(prompt):
while True:
try:
n = int(input(prompt))
if n <= 0:
raise ValueError("Must be positive")
return n
except ValueError as e:
print(f"Invalid: {e}. Try again.")
age = get_positive_int("Age: ")
When NOT to Use try/except
- For control flow (use
ifinstead) - To hide bugs (handle specific errors only)
- For conditions you can check first (e.g. check key exists before accessing)
HKDSE Context
Exception handling appears occasionally in HKDSE, mainly for input validation. Know the basic try/except/ValueError pattern.
Practise Error Handling
Build robust programs in PyForm that handle invalid input gracefully.
Start Coding โ