美文网首页程序员
自定义异常(经典案例)

自定义异常(经典案例)

作者: 小闫小闫同学 | 来源:发表于2018-11-06 11:12 被阅读7次

    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

    相关文章

      网友评论

        本文标题:自定义异常(经典案例)

        本文链接:https://www.haomeiwen.com/subject/jigyxqtx.html