사용자 지정 예외

<aside> 💡 파이썬에 기본으로 정의되어 있지 않은 예외를 발생시켜야 하는 경우 직접 만들어 사용합니다.

</aside>

class MonthTypeException(Exception):
    def __init__(self, month):
        self.message = f"{month}는 {type(month)}입니다."
        self.code = "123"
        super().__init__("정수를 입력하세요.")

    def __str__(self):
        return f"Error Code {self.code} : {self.message}"

class MonthRangeException(Exception):
    def __init__(self):
        super().__init__("1~12 사이의 숫자를 입력하세요.")
def pick_vacation_month(month):
    try:
        if not isinstance(month, int):
            raise MonthTypeException(month)
        if not 1 <= month <= 12:
            raise MonthRangeException()

        print(f"{month}월로 휴가 신청 완료되었습니다")

    except MonthTypeException as mte:
        mte_str = str(mte)
        print(mte_str) # 🔴

    except MonthRangeException as mre:
        mre_str = str(mre)
        print(mre_str) # 🔴
pick_vacation_month(3)
# pick_vacation_month(3.14)
# pick_vacation_month(15)

에러 버블링

<aside> 💡 함수가 다른 함수를 호출할 경우, 하위 함수에서 발생한 에러가 상위 함수로 전달되는 것을 말합니다.

</aside>

def func1():
    print("func1 실행")
    raise Exception('에러 발생')
    print("func1 완료")

def func2():
    print("func2 실행")

    func1() # 아래로 대체해 볼 것
    # try:
    #     func1()
    # except Exception as e:
    #     print(f"{e} 처리")

    print("func2 완료")

def func3():
    print("func3 실행")
    func2()
    print("func3 완료")

def func4():
    print("func4 실행")

    try:
        func3()
    except Exception as e:
        print(f"{e} 처리")

    print("func4 완료")

func4()