自定义异常(经典案例)

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 <module>

    xm = Person("小明",160)

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

    raise AgeError(age)

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容