Python Practice › Exception Handling Programs › Program 5
Several except blocks
Write a Python function that handles TypeError and ZeroDivisionError separately.
Input
(8, 4), (8, 0), (8, "2")
Output
2.0 error: division by zero error: cannot divide int by str
Approach
- One
exceptblock per error type.
Solution
def divide(a, b): try: return a / b except ZeroDivisionError: return "error: division by zero" except TypeError: return f"error: cannot divide {type(a).__name__} by {type(b).__name__}" for a, b in [(8, 4), (8, 0), (8, "2")]: print(divide(a, b))Output
2.0 error: division by zero error: cannot divide int by str
Learn the concept
New to this topic? Read the lesson, then come back.