exceptAdvanced Examples

Catches and handles exceptions raised in a try block

Exception groups (Python 3.11+)

Handling multiple simultaneous exceptions.

python
# ExceptionGroup for multiple errors
errors = []
for i, val in enumerate(["1", "abc", "3", "xyz", "5"]):
    try:
        int(val)
    except ValueError as e:
        errors.append(e)

if errors:
    print(f"Got {len(errors)} errors:")
    for e in errors:
        print(f"  {e}")

# Simulating except* behavior
class ValidationError(Exception):
    pass

class FormatError(Exception):
    pass

def validate_all(data):
    errs = []
    if not data.get("name"):
        errs.append(ValidationError("name required"))
    if not data.get("email"):
        errs.append(ValidationError("email required"))
    if data.get("age") and not isinstance(data["age"], int):
        errs.append(FormatError("age must be int"))
    if errs:
        raise ExceptionGroup("validation failed", errs)

try:
    validate_all({"age": "old"})
except ExceptionGroup as eg:
    print(f"Group: {eg}")
    for e in eg.exceptions:
        print(f"  {type(e).__name__}: {e}")

Python 3.11 introduced ExceptionGroup and except* for handling multiple exceptions at once, useful for concurrent operations and batch validation.

Want to try these examples interactively?

Open Advanced Playground