8. Errors and Exceptions错误和异常¶
Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. 到目前为止,错误消息还没有被提及,但是如果你已经尝试了这些例子,你可能已经看到了一些。There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.有(至少)两种可区分的错误:语法错误和异常。
8.1. Syntax Errors语法错误¶
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:语法错误,也称为解析错误,可能是您在学习Python时最常见的抱怨:
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. 解析器重复出现问题的行,并显示一个小“箭头”,指向检测到错误的行中最早的点。The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function 该错误是由箭头前面的标记引起的(或至少在该标记处检测到):在本例中,该错误是在函数print()
, since a colon (':'
) is missing before it. print()
处检测到的,因为它前面缺少冒号(':'
)。File name and line number are printed so you know where to look in case the input came from a script.打印文件名和行号,以便在输入来自脚本的情况下知道在哪里查找。
8.2. Exceptions异常¶
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. 即使语句或表达式在语法上是正确的,当试图执行它时,也可能会导致错误。Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. 在执行过程中检测到的错误称为异常,并且不是无条件致命的:您很快就会学会如何在Python程序中处理它们。Most exceptions are not handled by programs, however, and result in error messages as shown here:然而,大多数异常都不是由程序处理的,会导致错误消息,如下所示:
>>> 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
The last line of the error message indicates what happened. 错误消息的最后一行指示发生了什么。Exceptions come in different types, and the type is printed as part of the message: the types in the example are 异常有不同的类型,类型作为消息的一部分打印:示例中的类型有ZeroDivisionError
, NameError
and TypeError
. ZeroDivisionError
、NameError
和TypeError
。The string printed as the exception type is the name of the built-in exception that occurred. 打印为异常类型的字符串是发生的内置异常的名称。This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). 这适用于所有内置异常,但不一定适用于用户定义的异常(尽管这是一个有用的约定)。Standard exception names are built-in identifiers (not reserved keywords).标准异常名称是内置标识符(不是保留关键字)。
The rest of the line provides detail based on the type of exception and what caused it.该行的其余部分提供了基于异常类型和原因的详细信息。
The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. 错误消息的前面部分以堆栈回溯的形式显示了异常发生的上下文。In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.通常,它包含一个堆栈回溯,列出源代码行;但是,它不会显示从标准输入读取的行。
Built-in Exceptions内置异常 lists the built-in exceptions and their meanings.列出了内置的异常及其含义。
8.3. Handling Exceptions处理异常¶
It is possible to write programs that handle selected exceptions. 可以编写处理选定异常的程序。Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the 看看下面的例子,它要求用户输入一个有效的整数,但允许用户中断程序(使用Control-C或操作系统支持的任何东西);请注意,用户生成的中断通过引发KeyboardInterrupt
exception.KeyboardInterrupt
异常发出信号。
>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
The try
statement works as follows.try
语句的工作原理如下。
First, the try clause (the statement(s) between the首先,执行try
andexcept
keywords) is executed.try
子句(try
和except
关键字之间的语句)。If no exception occurs, the except clause is skipped and execution of the如果没有发生异常,则跳过try
statement is finished.except
子句并完成try
语句的执行。If an exception occurs during execution of the如果在执行try
clause, the rest of the clause is skipped.try
子句期间发生异常,则跳过该子句的其余部分。Then, if its type matches the exception named after the然后,如果其类型与以except
keyword, the except clause is executed, and then execution continues after the try/except block.except
关键字命名的异常匹配,则执行except
子句,然后在try
/except
块之后继续执行。If an exception occurs which does not match the exception named in the except clause, it is passed on to outer如果出现与try
statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.except
子句中指定的异常不匹配的异常,则将其传递给外部try
语句;如果没有找到处理程序,则它是一个未处理的异常,执行将停止,并显示一条消息,如上图所示。
A try
statement may have more than one except clause, to specify handlers for different exceptions. try
语句可能有多个except
子句,用于为不同的异常指定处理程序。At most one handler will be executed. 最多将执行一个处理程序。Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same 处理程序只处理相应try
statement. try
子句中出现的异常,而不处理同一try
语句的其他处理程序中出现的异常。An except clause may name multiple exceptions as a parenthesized tuple, for example:except
子句可以将多个异常命名为带括号的元组,例如:
... except (RuntimeError, TypeError, NameError):
... pass
A class in an 如果except
clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). except
子句中的类是同一个类或其基类,则它与异常兼容(但不是相反——列出派生类的except
子句与基类不兼容)。For example, the following code will print B, C, D in that order:例如,以下代码将按该顺序打印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")
Note that if the except clauses were reversed (with 请注意,如果except B
first), it would have printed B, B, B — the first matching except clause is triggered.except
子句被反转(首先是except B
),它将打印B、B、B——触发第一个匹配的except
子句。
All exceptions inherit from 所有异常都继承自BaseException
, and so it can be used to serve as a wildcard. BaseException
,因此它可以用作通配符。Use this with extreme caution, since it is easy to mask a real programming error in this way! 使用时要格外小心,因为这样很容易掩盖真正的编程错误!It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):它还可以用于打印错误消息,然后重新引发异常(允许调用方也处理异常):
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except BaseException as err:
print(f"Unexpected {err=}, {type(err)=}")
raise
Alternatively the last except clause may omit the exception name(s), however the exception value must then be retrieved from 或者,最后一个except子句可能会忽略异常名称,但是必须从sys.exc_info()[1]
.sys.exc_info()[1]
检索异常值。
The try
… except
statement has an optional else clause, which, when present, must follow all except clauses. try
… except
语句有一个可选的else
子句,当它出现时,必须在所有except
子句之后。It is useful for code that must be executed if the try clause does not raise an exception. 如果try
子句没有引发异常,那么它对于必须执行的代码非常有用。For example:例如:
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()
The use of the 使用else
clause is better than adding additional code to the try
clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try
… except
statement.else
子句比向try
子句添加其他代码要好,因为它可以避免意外捕获由try
… except
语句保护的代码未引发的异常。
When an exception occurs, it may have an associated value, also known as the exception’s argument. 当异常发生时,它可能有一个关联的值,也称为异常的参数。The presence and type of the argument depend on the exception type.参数的存在和类型取决于异常类型。
The except clause may specify a variable after the exception name. except
子句可以在异常名称后指定一个变量。The variable is bound to an exception instance with the arguments stored in 变量绑定到一个异常实例,其参数存储在instance.args
. instance.args
中。For convenience, the exception instance defines 为方便起见,exception实例定义了__str__()
so the arguments can be printed directly without having to reference .args
. __str__()
以便可以直接打印参数,而不必引用.args
。One may also instantiate an exception first before raising it and add any attributes to it as desired.也可以在引发异常之前先实例化异常,并根据需要向其添加任何属性。
>>> 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
If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions.如果异常有参数,它们将作为未处理异常消息的最后一部分(“详细信息”)打印。
Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. 异常处理程序不仅处理在try
子句中立即发生的异常,还处理在try
子句中调用(甚至间接调用)的函数中发生的异常。For example:例如:
>>> 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
8.4. Raising Exceptions抛出异常¶
The raise
statement allows the programmer to force a specified exception to occur. raise
语句允许程序员强制发生指定的异常。For example:例如:
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
The sole argument to 要引发的唯一参数表示要引发的异常。raise
indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from 这必须是异常实例或异常类(从Exception
). Exception
派生的类)。If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:如果传递了异常类,则将通过调用其构造函数(不带参数)隐式实例化它:
raise ValueError # shorthand for 'raise ValueError()'
If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the 如果需要确定是否引发了异常,但不打算处理它,raise
statement allows you to re-raise the exception: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
8.5. Exception Chaining异常链接¶
The raise
statement allows an optional from
which enables chaining exceptions. raise
语句允许一个可选选项,从中启用链接异常。For example:例如:
# exc must be exception instance or None.
raise RuntimeError from exc
This can be useful when you are transforming exceptions. 这在转换异常时非常有用。For example:例如:
>>> 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
Exception chaining happens automatically when an exception is raised inside an 当在except
or finally
section. except
或finally
节中引发异常时,异常链接会自动发生。This can be disabled by using 这可以通过使用from None
idiom:from None
成语禁用:
>>> try:
... open('database.sqlite')
... except OSError:
... raise RuntimeError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError
For more information about chaining mechanics, see Built-in Exceptions.有关链接机制的更多信息,请参阅内置异常。
8.6. User-defined Exceptions用户定义异常¶
Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). 程序可以通过创建新的异常类来命名自己的异常(有关Python类的更多信息,请参阅类)。Exceptions should typically be derived from the 异常通常应该直接或间接地从Exception
class, either directly or indirectly.Exception
类派生。
Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.异常类可以定义为任何其他类都可以做的事情,但通常保持简单,通常只提供一些属性,允许异常处理程序提取有关错误的信息。
Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.大多数异常都是以“Error”结尾的名称定义的,与标准异常的命名类似。
Many standard modules define their own exceptions to report errors that may occur in functions they define. 许多标准模块定义自己的异常,以报告它们定义的函数中可能发生的错误。More information on classes is presented in chapter Classes.有关课程的更多信息,请参阅类章节。
8.7. Defining Clean-up Actions定义清理操作¶
The try
statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. try
语句还有一个可选子句,用于定义在任何情况下都必须执行的清理操作。For example:例如:
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
If a 如果存在finally
clause is present, the finally
clause will execute as the last task before the try
statement completes. finally
子句,finally
子句将作为try
语句完成之前的最后一个任务执行。The 无论try语句是否生成异常,finally
clause runs whether or not the try
statement produces an exception. finally
子句都会运行。The following points discuss more complex cases when an exception occurs:以下几点讨论了发生异常时更复杂的情况:
If an exception occurs during execution of the如果在try
clause, the exception may be handled by anexcept
clause.try
子句的执行过程中发生异常,则该异常可以由except
子句处理。If the exception is not handled by an如果except
clause, the exception is re-raised after thefinally
clause has been executed.exception
子句未处理异常,则在执行finally
子句后会重新引发异常。An exception could occur during execution of an执行except
orelse
clause.except
子句或else
子句时可能会发生异常。Again, the exception is re-raised after the同样,在finally
clause has been executed.finally
子句执行之后,会重新引发异常。If the如果finally
clause executes abreak
,continue
orreturn
statement, exceptions are not re-raised.finally
子句执行break
、continue
或return
语句,则不会重新引发异常。If the如果try
statement reaches abreak
,continue
orreturn
statement, thefinally
clause will execute just prior to thebreak
,continue
orreturn
statement’s execution.try
语句到达break
、continue
或return
语句,finally
子句将在break
、continue
或return
语句执行之前执行。If a如果finally
clause includes areturn
statement, the returned value will be the one from thefinally
clause’sreturn
statement, not the value from thetry
clause’sreturn
statement.finally
子句包含return
语句,则返回值将是finally
子句的return
语句中的值,而不是try
子句的return
语句中的值。
For example:例如:
>>> def bool_return():
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False
A more complicated example:一个更复杂的例子:
>>> 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'
As you can see, the 如您所见,finally
clause is executed in any event. finally
子句在任何情况下都会执行。The 通过分割两个字符串引发的TypeError
raised by dividing two strings is not handled by the except
clause and therefore re-raised after the finally
clause has been executed.TypeError
不由except
子句处理,因此在执行finally
子句后重新引发。
In real world applications, the 在现实世界的应用程序中,finally
clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.finally
子句对于释放外部资源(如文件或网络连接)非常有用,无论资源的使用是否成功。
8.8. Predefined Clean-up Actions预先确定的清理行动¶
Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. 有些对象定义了不再需要该对象时要执行的标准清理操作,无论使用该对象的操作是否成功。Look at the following example, which tries to open a file and print its contents to the screen.看看下面的例子,它试图打开一个文件并将其内容打印到屏幕上。
for line in open("myfile.txt"):
print(line, end="")
The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. 这段代码的问题是,在这部分代码完成执行后,它会让文件保持不确定的打开时间。This is not an issue in simple scripts, but can be a problem for larger applications. 这在简单的脚本中不是一个问题,但在大型应用程序中可能是一个问题。The with
statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.with
语句允许使用文件等对象,以确保它们始终被及时、正确地清理。
with open("myfile.txt") as f:
for line in f:
print(line, end="")
After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. 执行语句后,文件f始终关闭,即使在处理行时遇到问题。Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.像文件一样,提供预定义清理操作的对象将在其文档中指出这一点。