什么是异常

python异常捕获,在刚开始学的时候,经常会遇到两种报错信息:语法错误和执行的异常。

语法错误在执行的时候就会报错,同时控制端会告诉你错误所在的行;
但即便python程序语法是正确的,在运行它的时候,也有可能发生错误。比如请求的接口返回空,没有做判断直接拿这个变量进行下一步逻辑处理,就会出现代码异常。

大多数的异常都不会被程序处理,都以错误信息的形式展现在这里:

>>> 10 * (1/0)             # 0 不能作为除数,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero

>>> 4 + spam*3             # spam 未定义,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined

>>> '2' + 2               # int 不能与 str 相加,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

异常以不同的类型出现,这些类型都作为信息的一部分打印出来。例子中的类型有 ZeroDivisionError,NameError 和 TypeError。

常用标准异常类

使用案例

try/except

异常捕捉可以使用 try/except 语句。

try:
    num = int(input("Please enter a number: "))
    print(num)
except:
    print("You have not entered a number, please try again!")

PS D:\learning\git\work> python test.py
Please enter a number: 60
60
PS D:\learning\git\work> python test.py
Please enter a number: d
You have not entered a number, please try again!
PS D:\learning\git\work>

try 语句执行顺序如下:

  • 首先,执行 try 代码块。
  • 如果没有异常发生,忽略 except 代码块,try 代码块执行后结束。
  • 如果在执行 try 的过程中发生了异常,那么 try 子句余下的部分将被忽略。
  • 如果异常的类型和 except 之后的名称相符,那么对应的 except 子句将被执行。
  • 一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。

try/except...else

如果使用这个子句,那么必须放在所有的 except 子句之后。
else 子句将在 try 代码块没有发生任何异常的时候被执行。

try:
    test_file = open("testfile.txt", "w")
    test_file.write("This is a test file!!!")
except IOError:
    print("Error: File not found or read failed")
else:
    print("The content was written to the file successfully")
    test_file.close()
PS D:\learning\git\work> python test.py
The content was written to the file successfully
PS D:\learning\git\work>
  • 如果写入没有问题,就会走到 else 提示成功。

try-finally

无论是否异常,都会执行最后 finally 代码。

try:
    test_file = open("testfile.txt", "w")
    test_file.write("This is a test file!!!")
except IOError:
    print("Error: File not found or read failed")
else:
    print("The content was written to the file successfully")
    test_file.close()
finally:
    print("test")
PS D:\learning\git\work> python test.py
The content was written to the file successfully
test

raise

使用 raise 抛出一个指定的异常

def numb( num ):
    if num < 1:
        raise Exception("Invalid level!")
        # 触发异常后,后面的代码就不会再执行
try:
    numb(0)            # 触发异常
except Exception as err:
    print(1,err)
else:
    print(2)
PS D:\learning\git\work> python test.py
1 Invalid level!
PS D:\learning\git\work>

语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。
最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。

---- 钢铁 648403020@qq.com 02.08.2021

02-09 08:32