5. Multiple except
A single try can have several except blocks. Python checks them from top to bottom and runs the first one whose type matches:
- Write one
exceptline per exception type you want to handle. - For a given error, only one handler runs.
- Order matters: put more specific handlers before broader ones.
Exceptionmatches almost everything, so it goes last. - If no handler matches, the exception is not caught and the program stops.
Coming from JavaScript? JavaScript usually has a single catch; Python lets you write one typed handler per expected error.
Add a second except
Use try with int("abc") inside. Add an except ValueError block that prints Not a number and an except ZeroDivisionError block that prints Cannot divide by zero. The ValueError handler runs.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Catch the second error
Use the same two handlers, but put print(10 / 0) inside try. The division raises ZeroDivisionError, so its handler prints Cannot divide by zero.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Only the first matching handler runs
Use try with int("oops") inside. Add except ValueError that prints Bad value, then except Exception that prints Something else. ValueError matches the first handler, so the second one is skipped.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Handle two errors in a function
Define parse_and_divide(text) that returns 10 / int(text) from inside a try block. Add except ValueError that returns Not a number and except ZeroDivisionError that returns Cannot divide by zero. Print parse_and_divide("2"), then parse_and_divide("x"), then parse_and_divide("0").
Print exactly:
Create a free account to save your progress and unlock chapter 2.