python 异常处理 try

try:
 语句体
except 异常类型:
 处理语句
except 异常类型:

 处理语句

#请用户输入被除数,除数,然后计算相除的结果
while True:
    try:
        a = int(input("请输入数字:"))
        b = int(input("请输入数字:"))
        c = a / b
        print(c)
        break
    except ZeroDivisionError:
        print("除数不能为0")
    except ValueError:
        print("请输入数字")
print("结束")

try:
 语句体
except (异常类型1,异常类型2):
 处理语句
except Exception;
 所有异常

try:
    1/0
    open("xxx.txt")
    print(num)
    print("------2-----")
except (NameError,FileNotFoundError):
    print("如果捕获到异常后做的 处理...")
except Exception as ie:  #Exception是捕获所有的异常
    print("如果用了Exception,那么一味只是上面的except没有捕获到异常except一定会捕获到,这个")
    print(ie)
else:
    print("没有异常才会执行的功能")
finally:
    print("---------finally---------")
print("-----3------")
try:
 语句体
except 异常类型 as 名称:
 print(名称)

def test():
    list1 = [1,2,3,4,5]
    list1[len(list1)]
def testError():
    try:
        test()
    except IndexError as ie:
        print("下标越界")
        print(ie)
testError()

异常可以镶嵌

import time
try:
    f = open("test.txt")
    try:
        while True:
            contet = f.readline()
            if len(contet) == 0:
                break
            time.sleep(2)  # 让打印是延迟两秒
            print(contet)
    except:
        #如果在读取文件的过程中,产生了异常,那么久会捕获到
        #比如 按下了 ctrl+c  结束程序
        pass
    finally:  # finally用来关闭文件
        f.close()
        print("关闭文件")
except:
    print("没有这个文件")




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值