Group the exception classes into a parenthesized tuple after except—writing except (ValueError, KeyError, TypeError) as err:—so Python catches any of the listed exceptions in one handler and binds the raised instance to err.
Basic Example
def parse_user_age(payload: dict, key: str) -> int | None:
try:
raw_value = payload[key]
return int(raw_value)
# 1. Recommended: Catch multiple exceptions using a parenthesized tuple
except (KeyError, TypeError, ValueError) as err:
print(f"Invalid input ({type(err).__name__}): {err}")
return None
print(parse_user_age({"age": "29"}, "age")) # Output: 29
print(parse_user_age({}, "age")) # Output: Invalid input (KeyError): 'age'
print(parse_user_age({"age": "abc"}, "age")) # Output: Invalid input (ValueError): invalid literal for int()...
print(parse_user_age({"age": None}, "age")) # Output: Invalid input (TypeError): int() argument must be a string...
Key Details & Edge Cases
- Parentheses are mandatory (
except ValueError, TypeError:is aSyntaxError):- In Python 3, writing
except ValueError, TypeError:without parentheses raisesSyntaxError: multiple exception types must be parenthesized(in legacy Python 2, that syntax bound the exception instance to the variable nameTypeErrorinstead of catching both!). Always wrap multiple exception types in parentheses:except (ValueError, TypeError):.
- In Python 3, writing
- Exception inheritance order when mixing
exceptblocks:- Inside a single tuple
(OSError, FileNotFoundError), order does not matter because all listed exceptions run the exact same handler. - However, if you use separate
exceptblocks alongside a multi-exception block, place more specific subclasses (likeFileNotFoundError) before broader base classes (likeOSError), or the base class will intercept them first.
- Inside a single tuple
- Sharing a tuple of exceptions across multiple
tryblocks:- Because
exceptaccepts any tuple of exception classes, you can store reusable exception groups in a module-level constant:NETWORK_ERRORS = (ConnectionError, TimeoutError, OSError) try: fetch_data() except NETWORK_ERRORS as err: retry_later(err)
- Because
except (...)vs.except* (...)(ExceptionGroupin Python 3.11+):- Standard
except (ValueError, TypeError):catches a single raised exception matching one of those types. - When working with concurrent tasks (
asyncio.TaskGroup) that can raise multiple simultaneous errors wrapped in anExceptionGroup, use Python 3.11+'sexcept* (ValueError, TypeError) as eg:syntax to split and handle matching sub-exceptions independently.
- Standard
- Avoid catching
BaseExceptionor bareexcept::- Never include
BaseException(or use bareexcept:) when grouping errors—that accidentally swallowsKeyboardInterrupt(Ctrl+C) andSystemExit, preventing users or process managers from stopping your script cleanly.
- Never include
Comparison of Multi-Exception Handling Patterns in Python
| Pattern | Syntax | Catches Multiple Concurrent Errors? | Binds Exception Instance? | Best Used When |
|---|---|---|---|---|
Tuple in except (Standard) |
except (ValueError, TypeError) as e: |
No (handles one raised exception) | Yes (e) |
Multiple distinct failure modes require the exact same recovery or fallback logic. |
| Reusable Exception Tuple | except RETRIABLE_ERRORS as e: |
No | Yes (e) |
Sharing a consistent set of network, I/O, or parsing exceptions across multiple functions. |
Separate except Clauses |
except KeyError: ... except ValueError: ... |
No | Yes (per clause) | Different exception types require distinct error messages, status codes, or recovery steps. |
| Common Base Exception | except OSError as e: |
No | Yes (e) |
Catching an entire built-in or custom exception hierarchy (FileNotFoundError, PermissionError, etc.). |
Exception Group (except*) |
except* (ValueError, TypeError) as eg: |
Yes (Python 3.11+ ExceptionGroup) |
Yes (eg sub-group) |
Handling multiple parallel failures raised concurrently inside asyncio.TaskGroup. |
You must log in or register to comment.
