PYTHON · 예외처리
ExceptionGroup (3.11+)
ExceptionGroup으로 여러 예외를 동시에 처리합니다. except* 구문과 함께 사용됩니다.
예외처리고급ExceptionGroupexcept*예외 그룹3.11
핵심 설명
ExceptionGroup으로 여러 예외를 동시에 처리합니다. except* 구문과 함께 사용됩니다.
Python code
# ExceptionGroup 생성
def validate(data: dict) -> None:
errors = []
if not data.get("name"):
errors.append(ValueError("이름은 필수입니다"))
if not isinstance(data.get("age", ""), int):
errors.append(TypeError("나이는 정수여야 합니다"))
if data.get("age", 0) < 0:
errors.append(ValueError("나이는 양수여야 합니다"))
if errors:
raise ExceptionGroup("검증 실패", errors)
# except* 로 선택적 처리
try:
validate({"name": "", "age": "스물"})
except* ValueError as eg:
print(f"ValueError ({len(eg.exceptions)}개):")
for e in eg.exceptions:
print(f" - {e}")
except* TypeError as eg:
print(f"TypeError ({len(eg.exceptions)}개):")
for e in eg.exceptions:
print(f" - {e}")
# ExceptionGroup 조합
try:
raise ExceptionGroup("다중 오류", [
ValueError("값 오류"),
ExceptionGroup("네트워크 오류", [
ConnectionError("연결 실패"),
TimeoutError("타임아웃"),
]),
])
except* (ConnectionError, TimeoutError) as eg:
print(f"네트워크 문제: {len(eg.exceptions)}개")
except* ValueError as eg:
print(f"값 문제: {len(eg.exceptions)}개")학습 팁
except*는 여러 절이 동시에 매칭될 수 있어 각 예외 유형을 독립적으로 처리합니다.
주의할 점
except*와 except를 같은 try 블록에 혼합할 수 없습니다.
자주 묻는 질문
ExceptionGroup (3.11+)란 무엇인가요?
ExceptionGroup 으로 여러 예외를 동시에 처리합니다. except* 구문과 함께 사용됩니다.
ExceptionGroup (3.11+) 학습 시 주의할 점은 무엇인가요?
except* 와 except 를 같은 try 블록에 혼합할 수 없습니다.