Exception이 발생되어 프로그램이 더 이상 실행될 수 없는 상황을 처리(handling)해서 정상화 시키는 작업을 말한다.
try - except 구문을 이용해 처리한다.
try:
Exception 발생가능한 코드 블록
except [Exception클래스 이름 [as 변수]] :
처리 코드
try block
except block
print("시작") # 1. try: n = input("정수:") # 2 num = int(n) # 3 -> n이 숫자 형태가 아닌경우: ValueError i = 10 / num # 4 -> num이 0일때: ZeroDivisionError j = i * 3 # 5 print(j) # 6 print(z) # 7 ---> NameError except ValueError: #### ValueError만 처리 # try에서 exception 발생시 처리할 코드. print("숫자로 변환할 수 없는 문자열을 입력해서 실행도중 예외가 발생했습니다.") # E-1 except ZeroDivisionError: #### ZeroDivisionError 만 처리 # E-2 print("0은 입력하지 마세요.") except: ### 위에 두개 Exception을 제외한 모든 Exception을 처리. # E-3 print("문제가 발생했어요.") print("종료") # 8 ##3에서 ValueError발생 # 1 -> 2 -> 3(X) -> E-1 -> 8 # # 4에서 ZeroDivisionError발생 # 1 -> 2 -> 3 ->4(X) -> E-2 -> 8 # # 7에서 NameError 발생 # 1 -> 2 -> 3 -> 4-> 5 ->6 -> 7(X) -> E-3시작
정수: 10
3.0
문제가 발생했어요.
종료int("aaa")
ValueError Traceback (most recent call last)
Cell In[13], line 1
----> 1 int("aaa")
ValueError: invalid literal for int() with base 10: 'aaa'10 / 0
ZeroDivisionErrorTraceback (most recent call last)
Cell In[16], line 1
----> 1 10 / 0
ZeroDivisionError: division by zeroprint(z) # 없는 변수 사용
NameError Traceback (most recent call last)
Cell In[26], line 1
----> 1 print(z) # 없는 변수 사용
NameError: name 'z' is not defined
예외 발생여부, 처리 여부와 관계없이 무조건 실행되는 코드블록
finally 는 except 보다 먼저 올 수 없다.
try: print("1") print(k) # print(10/0) except NameError: print(2) finally: print("무조건")1
2
무조건
파이썬은 Exception 상황을 클래스로 정의해 사용한다.
구현
#잘못된 날짜(월, 일)를 입력하면 발생시킬 Exception 을 정의 class WrongDateException(Exception): def __init__(self, wrong_month=-1, wrong_date=-1): # 잘못된 월, 일을 받아서 attribute 로 저장. self.__wrong_month = wrong_month self.__wrong_date = wrong_date @property def wrong_month(self): return self.__wrong_month @property def wrong_date(self): return self.__wrong_date def __str__(self): # 에러메세지를 반환. return f"잘못입력한 월: {self.wrong_month}, 잘못 입력한 일: {self.wrong_date}"e = WrongDateException(300, 200) e.wrong_month, e.wrong_date(300, 200)
Exception을 강제로 발생시킨다.
raise와 return
def save_month(month): # 월을 받아서 월을 저장하는 함수 if month < 1 or month > 12: raise WrongDateException(wrong_month=month) else: print(month, "월을 저장했습니다.") def save_date(date): if date < 1 or date > 31: raise WrongDateException(wrong_date=date) print(date, "일을 저장합니다.") def save(month, date): try: save_month(month) save_date(date) print("저장완료") except WrongDateException as e: # 예외클래스 as 변수명 : 변수에 발생된 Exception객체가 대입 print("예외발생:", e) print(e.wrong_month, e.wrong_date) print("종료")save(10000, 7)
WrongDateExceptionTraceback (most recent call last)
Cell In[79], line 1
----> 1 save(10000, 7)
Cell In[78], line 15, in save(month, date)
13 def save(month, date):
14 # try:
---> 15 save_month(month)
16 save_date(date)
17 print("저장완료")
Cell In[78], line 4, in save_month(month)
1 def save_month(month):
2 # 월을 받아서 월을 저장하는 함수
3 if month < 1 or month > 12:
----> 4 raise WrongDateException(wrong_month=month)
5 else:
6 print(month, "월을 저장했습니다.")
WrongDateException: 잘못입력한 월: 10000, 잘못 입력한 일: -1