异常处理
try:
num=int('asda')
print(num)
except IndexError as e:
print("chucuola")
except Exception as e:
print(e)
else:
print("helo")
finally:
print("the pro is end")
执行路径
- try–代码报错–except–finally
- try–代码正常–else—-finally
手动触发异常
try:
num=int(12)
print(num)
raise ImportError
except IndexError as e:
print("chucuola")
except Exception as e:
print("import error")
else:
print("helo")
finally:
print("the pro is end")
12
import error
the pro is end
执行路径: 代码报错–except–finally
异常使用实例
需求1:
持续输入:
直接回车,不算
ctrl+c无法退出
输入的是非数字
已上这三种异常均需要扑捉并提示try again
一共有3次猜测机会
num = 0
while True:
try:
if(int(input("a num > "))) == 100:
print("correct")
break
if num == 3:
print("th coreect num is 100")
else:
print("try again")
num += 1
except(KeyboardInterrupt,IOError,ValueError):
print("pls input a num")
需求2:
输入n后退出
输入nxxxx也退出
其他输入均表示继续
while True:
try:
op = input("Again?[y]").lower()
if op and op[0]=="n":
break
except(KeyboardInterrupt,EOFError):
print("pls input a y/n")