Python Mid_Exception(예외)

jaam._.mini·2023년 11월 8일
0

📒Python 기초 수학

목록 보기
6/46

어렵고 이해가 가지 않은 부분을 직접 찾아 정리해보았다.
기초가 없다보니 아직은 수업만으로 이해가되지 않아 여기저기 검색하며 추가적으로 공부하고 있다...😭


📒super()

--------------------------------------
class NotUseZeroException(Exception):
	def __init__(self, n):
    super(), __init__(f'{n}은 사용 X')
--------------------------------------

✅ def __init__
[새로 정의해 준다]

'새로 정의'해주었기 때문에 덮어써지면서(초기화됨)
Exception의 '변수'를 사용할 수 없게 된 것이다.

따라서, Exception의 '변수'를 사용하고 싶다면.
super().__init__()을 써야 한다.

( Tree에서 "def __init__()"을 하지 않으면 Exception의 변수를 그대로 사용할 수 있다 )

✅ super().__init__()
[Exception에서  정의된 '__init__변수'를  가져다 쓰겠다는 뜻]

📒class --(Exception)

[사용자 예외]

✅ class가 Exception 상속
⭐ 사용자 예외 클래스는 무조건, Exception을 상속받아야 예외class가 될 수 있다.

class NotUseZeroException(Exception):
    def __init__(self, n):
        super().__init__(f'{n}은 사용할 수 없습니다.') 
        ✅ super는 Exception의 변수 사용
def divCalculator(num1, um2):
        if num2 == 0:
            raise NotUseZeroException(num2) ✅ 내가 만든 예외 클래스를 발생
        else:
            print(f'{num1}/{num2} = {num1/num2}')

num1 = int(input('num1  :'))
num2 = int(input('num2  :')) 

try:
    divCalculator(num1, num2) ✅ 함수 호출
except NotUseZeroException as e: ✅ 예외가 발생하면 'except'으로 처리
    print(e) ✅ error 내용 출력

📝예제

class PwLengthShortException(Exception):
    def __init__(self, str):
        super().__init__(f'{str} : 길이 5미만')
class PwLengthLongException(Exception):
    def __init__(self, str):
        super().__init__(f'{str} : 길이 10초과')
class PwLengthWrongException(Exception):
    def __init__(self, str):
        super().__init__(f'{str} : 잘못된 비밀번호')

adminPw = input('pw : ')

try:
    if len(adminPw) < 5:
        raise PwLengthShortException(adminPw)
    elif len(adminPw) > 10:
        raise PwLengthLongException(adminPw)
    elif len(adminPw) != adminPw:
        raise PwLengthWrongException(adminPw)
    elif len(adminPw) == adminPw:
       print('맞음')

except PwLengthShortException as e1:
    print(e1)
except PwLengthLongException as e2:
    print(e2)
except PwLengthWrongException as e3:
    print(e3)

참고
https://blog.naver.com/ooumal/222619782637
# 제로베이스 데이터 취업 스쿨
# Daily study note
profile
비전공자의 데이터 공부법

0개의 댓글