一、什么是异常

异常:当检测到一个错误时,python解释器就无法继续执行了,反而出现一些错误提示,这就是所谓的异常(BUG)

二、python异常捕获方法

为什么捕获异常?
异常处理:对可能出现的bug提前准备、提前处理。
捕获异常作用:提前假设某处出现异常,做好提前准备,当真的出现异常的时候,可以有后续手段。

三捕获异常常用方法:

1、捕获常规异常 基本语法格式:

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

2、捕获指定异常 基本语法格式:

try:
    可能会发生错误的代码
except 指定异常1 as e
    如果出现指定异常要执行的代码

3、捕获多个异常 基本语法格式:

try:
    可能会发生错误的代码
except (指定异常1,指定异常2,指定异常3,.....)
    如果出现指定异常要执行的代码

4、捕获所有异常 基本语法格式:

try:
    可能会发生错误的代码
except Exception as e
    如果出现指定异常要执行的代码

5.异常else

else:表示如果没有异常要执行的代码
try:
    可能会发生错误的代码
except Exception as e
    如果出现指定异常要执行的代码
else:
    没有异常要执行的代码

6、异常 finally

finally:表示无论是否异常都需要执行的代码
基本语法格式:
try:
    可能会发生错误的代码
except Exception as e
    如果出现指定异常要执行的代码
else:
    没有异常要执行的代码
finally:
    无论是否异常都需要执行的代码

代码

捕获常规异常

try:
    f = open("test.txt","r",encoding="utf-8")
except:
    print("程序出现异常")
    f = open("test.txt","w",encoding="utf-8")

捕获指定异常

print(name)  # NameError : name 'name' is not defined
try:
    print(name)
except NameError as e:
    print("程序出现 NameError 异常!")
    print(e)

捕获多个异常

print(1 / 0)  # ZeroDivisionError

try:
    print(name)
    print(1 / 0)
except (NameError,ZeroDivisionError) as e:
    print("出现变量未定义或者零不能作为除数异常")
    print(e)

# print(1/0)

print("捕获异常后执行的代码")

捕获所有异常

try:
    f = open("wwwww.txt","r",encoding="utf-8")
    print(1 / 0)
    print(name)
except Exception as e:
    print("程序出现异常!")
    print(e)

异常else

try:
    # f = open("wwwww.txt","r",encoding="utf-8")
    # print(1 / 0)
    # print(name)
    print("hello")
except Exception as e:
    print("程序出现异常!")
    print(e)
else:
    print("没有异常要执行的代码!")

异常finally

try:
    f = open("wwwww.txt","r",encoding="utf-8")
    print(1 / 0)
    print(name)
    print("hello")
except Exception as e:
    print("程序出现异常!")
    print(e)
else:
    print("没有异常要执行的代码!")
finally:
    print("无论如何都要执行的代码!")

Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐