try~except~else
예외가 발생하지 않은 경우 실행하는 구문
예외가 발생하지 않은 경우 else에 적는다.
숫자가 아닌건 try~except로 '예외발생' , continue로 다시 올림
숫자면 else로 짝,홀수 판단으로 넘긴다.
finally
예외발생과 상관없이 실행
(ex. 외부자원 사용 시, 예외 발생과 상관없이 자원 해제를 해야 할 때가 있음. 그럴때 마지막으로 작성)
위 예외와 상관없이 inputdata 값 출력
짝,홀,실수 구분없이 데이터 전체 출력
Exception 클래스
예외 담당 클래스
raise 키워드 이용 시 예외 발생시킬 수 있다.
*args 는 exception 발생시킬 때 매개변수 두개 만들 때 둘 중 뭘 출력할지 정함.
사용자 Exception 클래스
NotUseZeroException을 지정
divCalculator 중 num2 =0 이면 예외발생, num2를 n으로 넘김
num1,2 입력받아서 try로 divCal 호출
num2가 0인 경우, n이 사용자 exception 클래스가 호출, 예외 발생
class PasswordLengthShortException(Exception):
def __init__(self,str):
super().__init__(f'{str} : 길이 5 미만')
class PasswordLengthLongException(Exception):
def __init__(self,str):
super().__init__(f'{str} : 길이 10 초과')
class PasswordWrongException(Exception):
def __init__(self,str):
super().__init__(f'{str}: 잘못된 비밀번호!')
while True:
try:
adminPW = input('input admin password: ')
if len(adminPW) < 5:
raise PasswordLengthShortException(adminPW)
elif len(adminPW) > 10:
raise PasswordLengthLongException(adminPW)
elif adminPW != 'admin1234':
raise PasswordWrongException(adminPW)
elif adminPW == 'admin1234':
print('빙고')
break
except PasswordLengthShortException as e1:
print(e1)
except PasswordLengthLongException as e2:
print(e2)
except PasswordWrongException as e3:
print(e3)
비밀번호 다시 입력하기