Python: Exceptions

Seoyul Kim·2020년 6월 10일
0

Python

목록 보기
14/16

Exceptions

여러 예외를 동일하게 처리

  • 여러 종류의 예외를 동일한 방식으로 처리할 경우에는 except 절에 처리할 예외를 괄호로 감싸고 콤마로 구별해 중복을 줄인다.
def get(self, request):
	try:
    
	except (IndexError, KeyError):
		return None

상주 범위 예외처리

  • except 절에서 상위 범주의 예외를 처리하면 그 범주에 속하는 하위 범주의 예외도 함께 처리된다. IndexError와 KeyError는 상위 범주 LookupError에 속하므로 두 error를 괄호로 묶어 exception 처리를 하지 않고, LookupError로 예외처리를 한다.
def get(self, request):
	try:
    
	except LookupError:
		return None

예외 객체 (except as)

  • except 절 안에서는 except 예외클래스 as 변수: 와 같이 처리할 예외 클래스 오른쪽에 as 변수 이름을 추가하여 예외 객체를 이용할 수 있다.
  • 예외를 가리키는 이름으로는 e, error, exception 등을 많이 사용한다.
def get(self, request):
	try:
    
	except Exception as e:
		return JsonResponse({'message':str(e)}, status=400)

ref) https://python.bakyeono.net/chapter-9-4.html#941-%EC%98%88%EC%99%B8%EC%9D%98-%EB%B6%84%EB%A5%98

0개의 댓글