Overview
Programs meet bad input. Catch exceptions so your code fails gracefully instead of crashing.
- try / except blocks
- Catching specific exceptions
- else and finally
Short Course
Code that might fail goes in a try block. If an error is raised, Python
jumps to the matching except block instead of crashing. Catch the
specific exceptions you expect — a bare except: hides real bugs.
def parse_age(text):
try:
return int(text)
except ValueError: # int("abc") raises ValueError
return None
parse_age("42") # -> 42
parse_age("abc") # -> None
Task
Write safe_divide(a, b) that returns a / b. If b is zero
(ZeroDivisionError) or the values can't be divided (TypeError),
return None instead.
Test Suites
Pending
Stdout