PYTHON · 예외처리
예외 처리 & 커스텀 예외
Python의 예외 계층과 올바른 예외 처리 패턴.
예외처리입문try-exceptfinallyelseraisefrom
핵심 설명
Python의 예외 계층과 올바른 예외 처리 패턴.
Python code
# 커스텀 예외 — 계층 구조 설계
class AppError(Exception):
"""애플리케이션 기반 예외"""
def __init__(self, message: str, code: int = 0):
super().__init__(message)
self.code = code
class ValidationError(AppError):
def __init__(self, field: str, message: str):
super().__init__(f"[{field}] {message}", code=400)
self.field = field
class NotFoundError(AppError):
def __init__(self, resource: str, id: int):
super().__init__(f"{resource} #{id} 없음", code=404)
# try / except / else / finally
def process(data: dict) -> str:
try:
value = data["key"] # KeyError 가능
result = int(value) # ValueError 가능
if result < 0:
raise ValidationError("key", "양수여야 함")
return f"결과: {result}"
except KeyError as e:
raise ValidationError("key", f"{e} 키 없음") from e
except ValueError as e:
raise ValidationError("key", "정수 변환 불가") from e
except ValidationError:
raise # 재발생
else:
# 예외 없을 때만 실행
print("성공")
finally:
# 항상 실행
print("정리")
# ExceptionGroup (Python 3.11+)
try:
raise ExceptionGroup("다중 오류", [
ValueError("값 오류"),
TypeError("타입 오류"),
])
except* ValueError as eg:
print(f"ValueError: {eg.exceptions}")
except* TypeError as eg:
print(f"TypeError: {eg.exceptions}")학습 팁
raise X from Y는 예외 체이닝입니다. 원인 예외가 __cause__에 저장되어 디버깅 시 원인 추적이 용이합니다.
주의할 점
except Exception:은 SystemExit, KeyboardInterrupt를 잡지 않지만 except BaseException:은 잡습니다. 대부분의 경우 Exception으로 충분합니다.
자주 묻는 질문
예외 처리 & 커스텀 예외란 무엇인가요?
Python의 예외 계층과 올바른 예외 처리 패턴.
예외 처리 & 커스텀 예외 학습 시 주의할 점은 무엇인가요?
except Exception: 은 SystemExit , KeyboardInterrupt 를 잡지 않지만 except BaseException: 은 잡습니다. 대부분의 경우 Exception 으로 충분합니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.