[py]python异常处理

来源:互联网 发布:mac phpstorm使用教程 编辑:程序博客网 时间:2024/06/15 10:53

异常处理

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 ImportErrorexcept IndexError as e:    print("chucuola")except Exception as e:    print("import error")else:    print("helo")finally:    print("the pro is end")
12import errorthe pro is end

执行路径: 代码报错–except–finally

异常使用实例

需求1:

持续输入:    直接回车,不算    ctrl+c无法退出    输入的是非数字    已上这三种异常均需要扑捉并提示try again    一共有3次猜测机会
num = 0while 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")

十以内加法训练器

原创粉丝点击