python 学习笔记(6)—— 错误和异常

参考:python 官方教学英文文档

错误和异常(Errors and Exceptions)

到目前为止,错误消息还没有被提及,但如果您尝试过这些示例,您可能已经看到了一些。有(至少)两种可区分的错误:语法错误和异常。

语法错误(Syntax Errors)

语法错误,也称为解析错误,可能是你在学习Python时最常见的一种抱怨:

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

解析器重复错误行,并显示一个小“箭头”,指向该行中最早检测到错误的点。错误是由箭头前面的标记引起的(或者至少是在箭头处检测到的):在本例中,错误是在函数print()处检测到的,因为它前面缺少冒号(‘:’)。文件名和行号会被打印出来,以便在输入来自脚本的情况下知道在哪里查找。

异常(Exceptions)

即使语句或表达式在语法上是正确的,在试图执行它时也可能导致错误。在执行过程中检测到的错误被称为异常,并且不是无条件致命的:您很快将学习如何在Python程序中处理它们。然而,大多数异常不会被程序处理,并导致如下所示的错误消息:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

错误消息的最后一行指出了发生了什么。异常有不同的类型,类型会作为消息的一部分打印出来:例子中的类型是ZeroDivisionErrorNameErrorTypeError。打印为异常类型的字符串是发生的内置异常的名称。这对所有内置异常都成立,但对用户定义的异常则不必成立(尽管这是一个有用的约定)。标准异常名是内置标识符(不是保留关键字)。这一行的其余部分提供了基于异常类型和导致异常的原因的详细信息。错误消息的前半部分以堆栈回溯的形式显示了异常发生的上下文。一般来说,它包含一个列出源代码行的栈回溯;但是,它不会显示从标准输入读取的行。

处理异常(Handling Exceptions)

可以编写处理所选异常的程序。看看下面的例子,它要求用户输入,直到输入一个有效的整数,但允许用户中断程序(使用Control-C或操作系统支持的任何方法);注意,用户生成的中断是通过抛出KeyboardInterrupt异常发出信号的。

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")

try语句的工作原理如下:

  • 首先,执行try子句(try和except关键字之间的语句)。
  • 如果没有异常发生,则跳过except子句,并结束try语句的执行。
  • 如果在执行try子句时发生异常,则跳过子句的其余部分。然后,如果异常的类型与except关键字命名的异常匹配,就执行except子句,然后在try/except代码块之后继续执行。
  • 如果发生了一个与except子句中命名的异常不匹配的异常,它将传递给外部的try语句;如果没有找到处理程序,它是一个未处理的异常,执行将停止,并显示如上所示的消息。

try语句可以有多个except子句,为不同的异常指定处理程序。最多执行一个处理程序。处理程序只处理发生在相应try子句中的异常,而不处理发生在同一try语句的其他处理程序中的异常。except子句可以将多个异常命名为圆括号内的元组,例如:

... except (RuntimeError, TypeError, NameError):
...     pass

except子句中的类如果是异常的同一个类或其基类,则与异常兼容(但反过来不行——列出派生类的except子句与基类不兼容)。例如,以下代码将按此顺序打印B、C、D:

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

注意,如果把except子句颠倒(except B在前面),它会打印B, B, B——触发第一个匹配的except子句。

当异常发生时,它可能有关联的值,也称为异常的参数。参数的存在和类型取决于异常类型。

except子句可以在异常名称之后指定一个变量。该变量绑定到异常实例,异常实例通常具有存储参数的args属性。为方便起见,内置异常类型定义了__str__()来打印所有参数,而无需显式访问.args

try:
    raise Exception('spam', 'eggs')
except Exception as inst:
    print(type(inst))    # the exception instance
    print(inst.args)     # arguments stored in .args
    print(inst)          # __str__ allows args to be printed directly,
                         # but may be overridden in exception subclasses
    x, y = inst.args     # unpack args
    print('x =', x)
    print('y =', y)
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

异常的__str__()输出作为未处理异常消息的最后一部分(’ detail ')打印出来。BaseException是所有异常的公共基类。它的子类之一Exception是所有非致命异常的基类。非Exception子类的异常通常不被处理,因为它们用于表示程序应该终止。它们包括由sys.exit()引发的SystemExit和当用户希望中断程序时引发的KeyboardInterrupt

Exception可以用作通配符,捕获(几乎)所有内容。然而,最好的做法是尽可能具体地指定我们打算处理的异常类型,并允许任何意外异常传播。处理异常最常见的模式是打印或记录异常,然后重新引发它(允许调用者也处理异常):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error:", err)
except ValueError:
    print("Could not convert data to an integer.")
except Exception as err:
    print(f"Unexpected {err=}, {type(err)=}")
    raise

except语句有一个可选的else子句,该子句出现时必须跟在所有except子句后面。对于那些如果try子句没有引发异常就必须执行的代码很有用。例如:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

使用else子句比在try子句中添加额外的代码更好,因为它可以避免意外捕获由try…except语句保护的代码没有引发的异常。

异常处理程序不仅处理在try子句中立即发生的异常,还处理在try子句中调用(甚至是间接调用)的函数内部发生的异常。例如:

def this_fails():
    x = 1/0

try:
    this_fails()
except ZeroDivisionError as err:
    print('Handling run-time error:', err)

Handling run-time error: division by zero

抛出异常(Raising Exceptions)

raise语句允许程序员强制发生指定的异常。例如:

>>> raise NameError('HiThere')
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	NameError: HiThere

raise的唯一实参指示要引发的异常。这必须是异常实例或异常类(派生自BaseException的类,如exception或其子类之一)。如果传递了一个异常类,它将通过调用不带参数的构造函数隐式实例化:

raise ValueError  # shorthand for 'raise ValueError()'

如果你需要确定是否引发了异常,但不打算处理它,raise语句的一种更简单的形式允许你重新引发异常:

>>> try:
		    raise NameError('HiThere')
		except NameError:
		    print('An exception flew by!')
		    raise

An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: HiThere

异常链(Exception Chaining)

如果一个未处理的异常发生在except部分中,它将附加被处理的异常并包含在错误消息中:

>>> try:
		    open("database.sqlite")
		except OSError:
		    raise RuntimeError("unable to handle error")

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: unable to handle error

为了指出一个异常是另一个异常的直接结果,raise语句允许一个可选的from子句:

# exc must be exception instance or None.
raise RuntimeError from exc

这在转换异常时非常有用。例如:

>>> def func():
		    raise ConnectionError

>>> try:
		    func()
		except ConnectionError as exc:
		    raise RuntimeError('Failed to open database') from exc

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in func
ConnectionError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database

它还允许使用from None习语禁用自动异常链接:

>>> try:
    open('database.sqlite')
except OSError:
    raise RuntimeError from None

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError

用户自定义异常

程序可以通过创建一个新的异常类来命名自己的异常(有关Python类的更多信息,请参阅“类”)。异常通常应该直接或间接地从Exception类派生。可以定义异常类,让它们做任何其他类可以做的事情,但通常保持简单,通常只提供一些属性,允许异常处理程序提取有关错误的信息。大多数异常都以“Error”结尾,类似于标准异常的命名。许多标准模块定义了自己的异常,以报告可能在其定义的函数中发生的错误。

定义清理行为

try语句有另一个可选子句,用于定义在所有情况下都必须执行的清理操作。例如:

>>> try:
		    raise KeyboardInterrupt
		finally:
		    print('Goodbye, world!')

Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>

如果存在finally子句,finally子句将作为try语句完成之前的最后一个任务执行。无论try语句是否产生异常,finally子句都会运行。以下几点讨论了发生异常时更复杂的情况:

  • 如果在try子句的执行过程中发生异常,则可以使用except子句处理异常。如果异常没有由except子句处理,则在finally子句执行后重新引发异常。
  • 在执行except或else子句时可能会发生异常。同样,在finally子句执行之后会重新引发异常。
  • 如果finally子句执行break、continue或return语句,则不会重新引发异常。
  • 如果try语句到达break、continue或return语句,finally子句将立即执行
  • 如果finally子句包含一个return语句,则返回值将是finally子句的return语句中的值,而不是try子句的return语句中的值。

例如:

>>> def bool_return():
		    try:
		        return True
		    finally:
		        return False

>>> bool_return()
False

一个更复杂的例子:

>>> def divide(x, y):
		    try:
		        result = x / y
		    except ZeroDivisionError:
		        print("division by zero!")
		    else:
		        print("result is", result)
		    finally:
		        print("executing finally clause")

>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

如您所见,finally子句在任何情况下都会被执行。除两个字符串引发的TypeError不会被except子句处理,因此会在finally子句执行后重新引发。

在实际应用程序中,finally子句用于释放外部资源(如文件或网络连接),而不管资源的使用是否成功。

预定义的清理行为

有些对象定义了在不再需要该对象时执行的标准清理操作,而不管使用该对象的操作是否成功或失败。请看下面的示例,它尝试打开一个文件并将其内容打印到屏幕上。

for line in open("myfile.txt"):
    print(line, end="")

这段代码的问题在于,在这部分代码完成执行后,它会让文件打开一段不确定的时间。这在简单的脚本中不是一个问题,但对于更大的应用程序来说可能是一个问题。with语句允许使用像文件这样的对象,以确保它们总是被及时和正确地清理。

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")

在执行语句之后,文件f总是关闭的,即使在处理这些行时遇到了问题。提供预定义清理操作的对象(如文件)将在其文档中指明这一点。

引发和处理多个不相关的异常

在某些情况下,有必要报告已经发生的几个例外情况。在并发框架中经常出现这种情况,当多个任务可能同时失败时,但也有其他用例,在这些用例中,需要继续执行并收集多个错误,而不是引发第一个异常。

内置的ExceptionGroup包装了一个异常实例列表,以便可以一起引发它们。它本身就是一个异常,因此可以像捕获任何其他异常一样捕获它。

>>> def f():
		    excs = [OSError('error 1'), SystemError('error 2')]
		    raise ExceptionGroup('there were problems', excs)

>>> f()
		  + Exception Group Traceback (most recent call last):
		  |   File "<stdin>", line 1, in <module>
		  |   File "<stdin>", line 3, in f
		  | ExceptionGroup: there were problems
		  +-+---------------- 1 ----------------
		    | OSError: error 1
		    +---------------- 2 ----------------
		    | SystemError: error 2
		    +------------------------------------
>>> try:
		    f()
		except Exception as e:
		    print(f'caught {type(e)}: e')

caught <class 'ExceptionGroup'>: e
>>>

通过使用except*而不是except,我们可以有选择地只处理组中匹配特定类型的异常。在下面的示例中,该示例显示了一个嵌套的异常组,每个except*子句从特定类型的组异常中提取,同时让所有其他异常传播到其他子句并最终重新引发。

>>> def f():
		    raise ExceptionGroup("group1",
		                         [OSError(1),
		                          SystemError(2),
		                          ExceptionGroup("group2",
		                                         [OSError(3), RecursionError(4)])])

>>> try:
		    f()
		except* OSError as e:
		    print("There were OSErrors")
		except* SystemError as e:
		    print("There were SystemErrors")

There were OSErrors
There were SystemErrors
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 2, in <module>
  |   File "<stdin>", line 2, in f
  | ExceptionGroup: group1
  +-+---------------- 1 ----------------
    | ExceptionGroup: group2
    +-+---------------- 1 ----------------
      | RecursionError: 4
      +------------------------------------
>>>

注意,嵌套在异常组中的异常必须是实例,而不是类型。这是因为在实践中异常通常是那些已经被程序引发并捕获的异常,遵循以下模式:

>>> excs = []
		for test in tests:
		    try:
		        test.run()
		    except Exception as e:
		        excs.append(e)

>>> if excs:
		   raise ExceptionGroup("Test Failures", excs)

对异常进行注释(Enriching Exceptions with Notes)

当为了引发异常而创建异常时,通常会用描述已发生错误的信息对其进行初始化。在有些情况下,在捕获异常后添加信息是有用的。为此,异常有一个add_note(note)方法,它接受一个字符串并将其添加到异常的注释列表中。标准回溯呈现包括所有注释,按照它们在异常之后添加的顺序。

>>> try:
		    raise TypeError('bad type')
		except Exception as e:
		    e.add_note('Add some information')
		    e.add_note('Add some more information')
		    raise

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: bad type
Add some information
Add some more information
>>>

例如,当将异常收集到异常组中时,我们可能希望为单个错误添加上下文信息。在下面的示例中,组中的每个异常都有一个注释,指示该错误发生的时间。

>>> def f():
		    raise OSError('operation failed')

>>> excs = []
>>> for i in range(3):
		    try:
		        f()
		    except Exception as e:
		        e.add_note(f'Happened in Iteration {i+1}')
		        excs.append(e)

>>> raise ExceptionGroup('We have some problems', excs)
		  + Exception Group Traceback (most recent call last):
		  |   File "<stdin>", line 1, in <module>
		  | ExceptionGroup: We have some problems (3 sub-exceptions)
		  +-+---------------- 1 ----------------
		    | Traceback (most recent call last):
		    |   File "<stdin>", line 3, in <module>
		    |   File "<stdin>", line 2, in f
		    | OSError: operation failed
		    | Happened in Iteration 1
		    +---------------- 2 ----------------
		    | Traceback (most recent call last):
		    |   File "<stdin>", line 3, in <module>
		    |   File "<stdin>", line 2, in f
		    | OSError: operation failed
		    | Happened in Iteration 2
		    +---------------- 3 ----------------
		    | Traceback (most recent call last):
		    |   File "<stdin>", line 3, in <module>
		    |   File "<stdin>", line 2, in f
		    | OSError: operation failed
		    | Happened in Iteration 3
		    +------------------------------------
>>>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zyw2002

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值