# ExceptionGroup for multiple errors
errors = []
for i, val inenumerate(["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* behaviorclassValidationError(Exception):
passclassFormatError(Exception):
passdefvalidate_all(data):
errs = []
ifnot data.get("name"):
errs.append(ValidationError("name required"))
ifnot data.get("email"):
errs.append(ValidationError("email required"))
if data.get("age") andnotisinstance(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}")
Output
Click "Run" to execute your code
Python 3.11 introduced ExceptionGroup and except* for handling multiple exceptions at once, useful for concurrent operations and batch validation.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?