[py]python异常处理

异常处理

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")

十以内加法训练器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值