Several except blocks

EasyException Handling Programs · 5 of 20

Write a Python function that handles TypeError and ZeroDivisionError separately.

Advertisement
Input
(8, 4), (8, 0), (8, "2")
Output
2.0
error: division by zero
error: cannot divide int by str

Approach

  1. One except block per error type.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment