一、什么是异常
异常是在程序运行过程中发生的错误,当异常发生时,需要对异常进行处理,否则整个程序将崩溃。
如下程序,运行会报错,抛出异常
print(1 / 0)
print("Done!")
输出:
Traceback (most recent call last): File "script.py", line 1, in <module> print(1 / 0) ZeroDivisionError: division by zero
除法中除数为0,抛出异常报错:ZeroDivisionError
异常,由于没有对异常进行处理,导致了程序的崩溃,后面的语句没有再继续执行。
二、异常处理
1、try-except
try
和 except
语句块可以用来捕获和处理异常,try
后面跟的是需要捕获异常的代码,except
后面跟的是捕获到异常后需要做的处理。每一个 try
语句块后面必须跟上一个 except
语句块,即使 except
语句块什么也不做。
try:
print(1 / 0)
except ZeroDivisionError:
print("ZeroDivisionError happened!")
print("Done!")
输出:
ZeroDivisionError happened!
Done!
由以上程序运行,可以发现程序能继续运行后续语句。
try
语句块后面可以跟上多个 except
语句块。
try:
print(1 / 0)
#除0异常
with open('test.log') as file:
#文件不存在异常
read_data = file.read()
except ZeroDivisionError:
print("ZeroDivisionError happened!")
except FileNotFoundError:
print("FileNotFoundError happened!")
print("Done!")
tips:打开文件的语句:
with open('文件路径') as file
#读取文件数据
read_data = file.read()
输出:
ZeroDivisionError happened!
Done!
代码中,先遇到了除0的错误,抛出了异常,所以没有执行后续的文件找不到异常,直接进行了异常处理。
2、try-except-else
try-except语句块后可以跟else分支,如果没有发生异常时,将会处理else分支里的程序块
try:
print(1 / 1)
except ZeroDivisionError:
print("ZeroDivisionError happened!")
else:
print("Exception not happened")
print("Done!")
输出:
1.0
Exception not happened
Done!
3、try-except-else-finally
try-except-else语句块后可以加finally处理,无论前面是否发生异常,都会执行finally内的程序块。
try:
print(1 / 1)
except ZeroDivisionError:
print("ZeroDivisionError happened!")
else:
print("Exception not happened")
finally:
print("Finally is executed!")
print("Done!")
输出:
1.0
Exception not happened
Finally is executed!
Done!
try:
print(1 / 0)
except ZeroDivisionError:
print("ZeroDivisionError happened!")
else:
print("Exception not happened")
finally:
print("Finally is executed!")
print("Done!")
输出:
ZeroDivisionError happened!
Finally is executed!
Done!
三、抛出异常
上面是针对异常发生的处理,我们也可以主动抛出异常。使用raise关键字主动抛出异常。
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
输出:
Traceback (most recent call last): File "script.py", line 3, in <module> raise Exception('x should not exceed 5. The value of x was: {}'.format(x)) Exception: x should not exceed 5. The value of x was: 10
由上面例子可看出,我们针对大于5的数字,处理为主动抛出异常。