Level: Intermediate | Prerequisite: Week 4
Learning Goals
- Know each section of
try/except/else/finally - Distinguish types of exceptions and handle them
- Create user-defined exceptions
- Intentionally raise exceptions (
raise)
1. What is an Exception
An error that occurs during execution. If not handled, the program terminates.
print(10 / 0) # ZeroDivisionError
print(int("abc")) # ValueError
print([1,2][5]) # IndexError
2. try / except
try:
n = int(input("Number:"))
print(10 / n)
except ValueError:
print("Not a number")
except ZeroDivisionError:
print("Cannot divide by 0")
except Exception as e:
print(f"Other error: {e}")
3. else / finally
else: Executes when try finishes without exceptionsfinally: Always executes regardless of exceptions (cleanup tasks)
try:
f = open("data.txt")
except FileNotFoundError:
print("No file")
else:
print(f.read())
f.close()
finally:
print("Cleanup complete")
4. raise
Intentionally raise an exception.
def withdraw(balance, amount):
if amount > balance:
raise ValueError("Insufficient balance")
return balance - amount
5. User-Defined Exceptions
Inherit from Exception.
class InsufficientFundsError(Exception):
pass
def transfer(account, amount):
if account.balance < amount:
raise InsufficientFundsError(f"Balance {account.balance} < Request {amount}")
6. Exception Chaining
Raise a new exception while wrapping an existing one.
try:
int("abc")
except ValueError as e:
raise RuntimeError("Input processing failed") from e
Key Examples (examples/)
| File | Content |
|---|---|
01_try_except.py |
Basic try/except |
02_else_finally.py |
else, finally |
03_raise.py |
raise and validation |
04_custom.py |
User-defined exception |
⚠️ Common Mistakes
- Too broad except
try: ... except: #All exceptions (including KeyboardInterrupt) — dangerous pass
→ Specify the narrowest possible exception class.
-
except ... as e: pass— Hides errors. At least log them. -
return in
finally— Can override return values of try. -
Order of except — Narrow exceptions (
FileNotFoundError) first, broader ones (OSError) later.
❓ FAQ
Q1. Should try be wrapped around every function? A. No. Only in places where recovery is possible. Usually user input, file I/O, network calls.
Q2. What is the difference between Exception and BaseException?
A. BaseException is the top-level. KeyboardInterrupt and SystemExit are also included. Generally, only up to Exception is caught.
Q3. Exception vs return value (None / -1)? A. Exceptions clearly indicate "not normal flow." For normal situations like "not found" in searches, None is recommended.
📝 Exercises (exercises/)
exercise1.md— safe integer input (read_int)exercise2.md— user-defined exception (InvalidScoreError)exercise3.md— file read exception handling
Next Week
Week 6. File Input/Output