【Python学习】——异常

一、异常

概念:程序运行中出现了错误

二、异常处理(捕获异常)

基本语法:

try:
可能发生错误的代码
except:
如果出现异常执行的代码

 try:
    f = open("D:/abc.txt", "r", encoding="UTF-8")
except:
    print("error!file not existed!")
    f = open("D:/abc.txt", "w", encoding="UTF-8")
    print("new file built")

捕获指定异常

注意:

  1. 如果尝试执行的代码的异常类型和要捕获的异常类型不一致,则无法捕获异常
  2. 一般try下方只放一行尝试执行的代码
try:
	print(name)
except NameError as e:
    print("name变量名称未定义错误")
    print(e)  # e是异常信息

在这里插入图片描述

捕获多个异常

try:
    1/0
except (NameError, ZeroDivisionError) as e:
    print("出现了未变量定义 或者 除以0的异常错误")
    print(e)

在这里插入图片描述

捕获所有异常

exception是顶级异常

try:
    f = open("D:/123.txt", "r")
except Exception as e:
    print(e)

在这里插入图片描述

else和finally语法

  • else
try:
    print("hello")
except Exception as e:
    print(e)
else:
    print("no error")

在这里插入图片描述

  • finally
    无论是否异常都要执行的代码,如关闭文件
try:
    f = open("D:/test.txt", "r")
except Exception as e:
    print("file not existed")
    f = open("D:/test.txt", "w")
    print("file built")
else:
    print("no error")
finally:
    print("finally")
    f.close()

第一次运行:
在这里插入图片描述
第二次运行(test.txt已创建)
在这里插入图片描述

三、异常的传递性

当函数func01中发生异常,并且没有捕获处理这个异常时,异常会传递到函数func02,当func02也没有捕获处理这个异常的时候main函数会捕获这个异常,这就是异常的传递性

def func01():
    print("func01 执行")
    1/0  # 异常
    print("func01 结束执行")


def func02():
    print("func02 执行")
    func01()
    print("func02 结束执行")

def main():
    func02()


main()

在这里插入图片描述
在main函数中捕获异常,修改代码为:

def main():
    try:
        func02()
    except Exception as e:
        print("error!")
        print(e)

在这里插入图片描述
作用:出现异常时不一定非要找到底层错误代码,在较高层级捕获也是可以的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值