Unit 11.4A · Term 4

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

Lesson Presentation

11.4A-lesson-23-exceptions.pdf · Slides for classroom use

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 runs

Common 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 zero

Pitfalls

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

  • else runs only if NO exception. finally ALWAYS 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

Remember

Name 5 Python exception types and their causes.

Understand

Explain else vs finally in try/except.

Apply

Write a function that safely converts a string to int with a default value on failure.

Apply

Read a file with error handling for missing file and invalid lines.

Analyze

What's wrong with try: x=int(input()); y=10/x except: pass?

Create

Build a robust calculator handling all input errors.

Self-Check Quiz

1. What keyword starts error handling?
Click to reveal answer
2. What exception does int('abc') raise?
Click to reveal answer
3. When does else execute?
Click to reveal answer
4. When does finally execute?
Click to reveal answer
5. How to capture the error message?
Click to reveal answer