Catch several errors in one block

EasyException Handling Programs · 6 of 20

Write a Python program that catches ValueError and TypeError in one except block.

Advertisement
Input
"12", "x", None
Output
24
'x': ValueError
None: TypeError

Approach

  1. Use a tuple of exception types.

Solution

Python
for value in ["12", "x", None]:    try:        print(int(value) * 2)    except (ValueError, TypeError) as e:        print(f"{value!r}: {type(e).__name__}")
Output
24
'x': ValueError
None: TypeError

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