데이터분석/둘째주
파이썬 Python : 사용자 예외 클래스
핑크댕댕이
2023. 10. 14. 03:22
728x90
사용자 예외 클래스
Exception 클래스를 상속해서 사용자 예외 클래스를 만들 수 있다.
【 class 사용자 예외 클래스명(Exception): 】
class NotUseZeroException(Exception):
def __init__(self, n):
super().__init__(f'{n}은 사용할 수 없습니다!')
def divCalculator(num1, num2):
if num2 == 0:
raise NotUseZeroException(num2)
else:
print(f'{num1} / {num2} = {num1/num2}')
num1 = int(input('number 1: '))
num2 = int(input('number 2: '))
try:
divCalculator(num1, num2)
except NotUseZeroException as ze:
print(ze)
-- 출력 -- |
number 1: 10 number 2: 0 0은 사용할 수 없습니다! |
728x90
[실습]
관리자 암호를 입력하고 다음 상태에 따라 예외 처리하는 예외 클래스를 만들어보자
- 암호 길이가 5미만인 경우 : PasswordLengthShortException
- 암호 길이가 10을 초과하는 경우 : PasswordLengthLongException
- 암호가 잘못된 경우 : PasswordWrongException
출력예시)
input admin password: 1234 1234: 길이 5미만!! |
input admin password: 12345678 12345678: 잘못된 비밀번호!! |
input admin password: administrator administrator: 길이 10초과!! |
input admin password: admin1234 빙고! |
반응형
#암호 길이가 5미만인 경우
class PasswordLengthShortException(Exception):
def __init__(self, password):
super().__init__(f'{password}: 길이 5미만!')
#암호 길이가 10을 초과하는 경우
class PasswordLengthLongException(Exception):
def __init__(self, password):
super().__init__(f'{password}: 길이 10초과!')
#암호가 잘못된 경우
class PasswordWrongException(Exception):
def __init__(self, password):
super().__init__(f'{password}: 잘못된 비밀번호!')
adminPw = input('input admin password: ')
if len(adminPw) < 5:
raise PasswordLengthShortException
elif len(adminPw) > 10:
raise PasswordLengthLongException
elif adminPw != 'admin1234':
raise PasswordWrongException
elif adminPw == 'admin1234':
print('빙고!')
except PasswordLengthShortException as e1:
print(e1)
except PasswordLengthLongException as e2:
print(e2)
except PasswordWrongException as e3:
print(e3)
반응형