自定义抛异常

Posted zhangliang689

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义抛异常相关的知识,希望对你有一定的参考价值。

 1 class AgeError(Exception):
 2 
 3     def __init__(self, age):
 4         self.age = age
 5 
 6     def __str__(self):
 7         return "您输入的年龄有误!%d"%self.age
 8 
 9 class Person(object):
10 
11     def __init__(self, name, age):
12         self.name = name
13         if age <= 0 or age >= 150:
14             raise AgeError(age)
15         else:
16             self.age = age
17 
18 try:
19     xm = Person("xiaoming", 300)
20 except Exception as e:
21     print("异常是%s"%e)

 

以上是关于自定义抛异常的主要内容,如果未能解决你的问题,请参考以下文章