Sobes.tech
Senior
207

What are the purposes of the BaseExceptionGroup and ExceptionGroup classes in Python?

Answer from AI

sobes.tech AI

BaseExceptionGroup and ExceptionGroup are designed to group multiple exceptions and raise them as a single object.

BaseExceptionGroup:

  • The base class for all exception groups.
  • Abstract, not used directly.
  • Contains common logic for handling exception groups.

ExceptionGroup:

  • A concrete class for grouping exceptions that are subclasses of Exception.
  • The most commonly used class for handling multiple errors in asynchronous code or parallel execution.
  • Allows handling individual exceptions within the group using except*.

Main features:

  • exceptions: Tuple of exceptions in the group.
  • message: Message describing the exception group.
  • subgroup(filter): Creates a new exception group containing only those exceptions from the original group that match the filter.
  • split(filter): Splits the group into two: one with exceptions matching the filter, and the other with the rest. Returns a tuple (matching_group, rest_group).

Example of using except*:

# Simulating functions that raise errors
def func1():
    raise ValueError("Error in func1")

def func2():
    raise TypeError("Error in func2")

# Grouping and handling exceptions
try:
    # Simulating execution of multiple tasks
    errors = []
    try:
        func1()
    except Exception as e:
        errors.append(e)
    try:
        func2()
    except Exception as e:
        errors.append(e)

    if errors:
        raise ExceptionGroup("Multiple errors during execution", errors)

except* ValueError as ve:
    # Handling only ValueError from the group
    print(f"Caught ValueError: {ve}")
except* TypeError as te:
    # Handling only TypeError from the group
    print(f"Caught TypeError: {te}")
except ExceptionGroup as eg:
    # Handling remaining (or the entire group if no matches)
    print(f"Caught remaining exception group: {eg}")