Exception Handling
Exceptions are runtime errors. The try/except
mechanism lets you handle errors gracefully instead of crashing.
Learning Objectives
- 11.4.2.1 Handle exceptions using try/except
Conceptual Anchor
The Safety Net
try = the tightrope walk (risky code). except = the safety net that
catches you if you fall.
Rules & Theory
try / except Syntax
try:
num = int(input("Enter number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("Not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")Full Structure
try:
data = open("data.txt").read()
except FileNotFoundError:
print("File not found!")
data = ""
else:
print(f"Read {len(data)} chars") # Only if NO error
finally:
print("Cleanup done") # ALWAYS runsCommon Exceptions
| Exception | Cause | Example |
|---|---|---|
ValueError |
Wrong value | int("hello") |
ZeroDivisionError |
Divide by 0 | 10 / 0 |
IndexError |
Bad index | [1,2][5] |
KeyError |
Missing key | d["x"] |
TypeError |
Wrong type | "3" + 5 |
FileNotFoundError |
No such file | open("x.txt") |
Worked Examples
1 Bulletproof Input
def get_integer(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid! Enter a whole number.")
age = get_integer("Enter your age: ")2 Safe File Reading
def read_scores(filename):
try:
with open(filename, "r") as f:
scores = []
for i, line in enumerate(f, 1):
try:
scores.append(int(line.strip()))
except ValueError:
print(f"Line {i} invalid, skipping")
return scores
except FileNotFoundError:
print(f"'{filename}' not found")
return []
scores = read_scores("grades.txt")
if scores:
print(f"Average: {sum(scores)/len(scores):.1f}")3 Safe Division
def safe_divide(a, b):
try:
return round(a / b, 4)
except ZeroDivisionError:
return "Error: division by zero"
except TypeError:
return "Error: numbers required"
print(safe_divide(10, 3)) # 3.3333
print(safe_divide(10, 0)) # Error: division by zeroPitfalls
Bare except:
A bare except: catches ALL errors including system ones. Always specify the type.
except: pass
Silently swallowing errors hides bugs. At minimum: except Exception as e: print(e)
Pro-Tips
Tips
elseruns only if NO exception.finallyALWAYS runs.- Put specific exceptions before general ones
except Exception as e:captures the error message- Input validation pattern:
while True: try: ... break except: ...
Graded Tasks
Name 5 Python exception types and their causes.
Explain else vs finally in try/except.
Write a function that safely converts a string to int with a default value on failure.
Read a file with error handling for missing file and invalid lines.
What's wrong with try: x=int(input()); y=10/x except: pass?
Build a robust calculator handling all input errors.