Catch several errors in one block
Write a Python program that catches ValueError and TypeError in one except block.
"12", "x", None
24 'x': ValueError None: TypeError
Approach
- Use a tuple of exception types.
Solution
for value in ["12", "x", None]: try: print(int(value) * 2) except (ValueError, TypeError) as e: print(f"{value!r}: {type(e).__name__}")24 'x': ValueError None: TypeError
Learn the concept
New to this topic? Read the lesson, then come back.