利用if条件避开异常
AGE=10
while True:
age=input('>>: ').strip()
if age.isdigit():
age=int(age)
if age == AGE:
print('you got it')
break
利用try…except
try:
int("jiao")
##如果try里面的是异常,则执行except里面的
except EOFError as e:
print(e)
except ImportError as e:
print(e)
except ValueError as e:
print(e)
万能异常Exception
try:
int("ad")
except Exception as e: ##只要是异常都能触发它
pass
自定义异常
class YuanErro(BaseException): ##必须继承于BaseException这个基类
def __init__(self, msg):
self.msg = msg
##需要重置__init__和__str__两个方法
def __str__(self):
return self.msg
try:
raise YuanErro("hehe!")
except YuanErro as e:
print(e)
hehe!