异常是程序运行过程中产生的错误,
except Exception as e: #抛出异常的固定格式
def chu(a, b):
return a/b
try:
ret = chu(10, 0)
print(ret)
except Exception as e:
print("除数不能是0")
运行结果会打印最后一个除数不能为0
class GenderException(Exception): # 自定义一个异常名称
pass
class Person:
def __init__(self,name,gender):
self.name = name
self.gender = gender
def jinqu(self):
if self.gender != "男":
raise GenderException ("性别不对")
else:
print("欢迎光临")
p3 = Person("小红","女")
p3.jinqu()
try:
p1 = Person("lowen","男")
p1.jinqu()
p2 = Person("李玉刚","性别不详")
p2.jinqu()
except GenderException as e:
print("出去,变态")
except Exception as e:
print("其他错误")
# p1因为符合程序要求会正常被执行,打印方法类的“欢迎光临”
#p2属于异常项目,但是只有两个条件,所有第一个条件已经被满足了就不会执行后面的错了