自定义异常(经典案例)

class AgeError(Exception):

    def __init__(self,age):

        self.__age= age

def __str__(self):

        return "你传入的年龄不满足需求:age=%d" % self.__age

class Person(object):

    def __init__(self,name,age):

        if 0 < age<=150:

            self.name= name

self.age= age

else:

            raise AgeError(age)

xm= Person("小明",160)

结果:

Traceback (most recent call last):

  File "E:/python/ITxiaoyan/day12/1.py", line 52, in

    xm = Person("小明",160)

  File "E:/python/ITxiaoyan/day12/1.py", line 51, in __init__

    raise AgeError(age)

__main__.AgeError: 你传入的年龄不满足需求:age=160

你可能感兴趣的:(自定义异常(经典案例))