qinkwl

覃空万里

导航

抛出异常

raise关键字

raise可以抛出自定义异常
大多数情况下,内置异常已经够用了。但是有时候你还是需要自定义一些异常:自定义异常应该继承Exception类,直接继承或者间接继承都可以

class CouponError01(Exception):
    def __init__(self):
        print("优惠券错误类型1")


class CouponError02(Exception):
    def __init__(self):
        print("优惠券错误类型2")


class CouponError03(Exception):
    def __init__(self):
        print("优惠券错误类型3")


def main():
    try:
        choice = input(">>>")

        if choice == "1":
            # 出现优惠券错误类型1
            raise CouponError01
        elif choice == "2":
            # 出现优惠券错误类型2
            raise CouponError02

        elif choice == "3":
            # 出现优惠券错误类型3
            raise CouponError03

        if random.randint(5, 10) > 5:
            # 出现优惠券错误类型2
            raise CouponError02

    except CouponError01 as e:
        print("解决优惠券错误类型1")

    except CouponError02 as e:
        print("解决优惠券错误类型2")

    except CouponError03 as e:
        print("解决优惠券错误类型3")


if __name__ == '__main__':
    main()

posted on 2024-12-29 21:08  覃空万里  阅读(8)  评论(0)    收藏  举报