How do you catch multiple exception types in a single except block in Python? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you catch multiple exception types in a single except block in Python?

message-square
0

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 a SyntaxError):
    • In Python 3, writing except ValueError, TypeError: without parentheses raises SyntaxError: multiple exception types must be parenthesized (in legacy Python 2, that syntax bound the exception instance to the variable name TypeError instead of catching both!). Always wrap multiple exception types in parentheses: except (ValueError, TypeError):.
  • Exception inheritance order when mixing except blocks:
    • Inside a single tuple (OSError, FileNotFoundError), order does not matter because all listed exceptions run the exact same handler.
    • However, if you use separate except blocks alongside a multi-exception block, place more specific subclasses (like FileNotFoundError) before broader base classes (like OSError), or the base class will intercept them first.
  • Sharing a tuple of exceptions across multiple try blocks:
    • Because except accepts 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)
      
  • except (...) vs. except* (...) (ExceptionGroup in 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 an ExceptionGroup, use Python 3.11+'s except* (ValueError, TypeError) as eg: syntax to split and handle matching sub-exceptions independently.
  • Avoid catching BaseException or bare except::
    • Never include BaseException (or use bare except:) when grouping errors—that accidentally swallows KeyboardInterrupt (Ctrl+C) and SystemExit, preventing users or process managers from stopping your script cleanly.

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.