8. Errors and Exceptions

8. 错误和异常

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

8.1. 语法错误

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 "", 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. File name and line number are printed so you know where to look in case the input came from a script.
解析器会输出出现语法错误的那一行,并显示一个“箭头”,指向这行里面检测到第一个错误。 错误是由箭头指示的位置 上面 的 token 引起的(或者至少是在这里被检测出的):在示例中,在 "print()" 这个函数中检测到了错误,因为在它前面少了个冒号 ("':'") 。文件名和行号也会被输出,以便输入来自脚本文件时你能知道去哪检查。



8.2. Exceptions

8.2. 异常

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. Most exceptions are not handled by programs, however, and result in error messages as shown here:
即使语句或表达式在语法上是正确的,但在尝试执行时,它仍可能会引发错误。在执行时检测到的错误被称为异常,异常不一定会导致严重后果:你将很快学会如何在Python程序中处理它们。 但是,大多数异常并不会被程序处理,此时会显示如下所示的错误信息:

   >>> 10 * (1/0) 
Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "", line 1, in
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't convert 'int' object to str implicitly
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". 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).
错误信息的最后一行告诉我们程序遇到了什么类型的错误。异常有不同的类型,而其类型名称将会作为错误信息的一部分中打印出来:上述示例中的异常类型依次是:"ZeroDivisionError", "NameError" 和 "TypeError"。作为异常类型打印的字符串是发生的内置异常的名称。对于所有内置异常都是如此,但对于用户定义的异常则不一定如此(虽然这是一个有用的规范)。标准的异常类型是内置的标识符(而不是保留关键字)。

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 happened, 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

8.3. 处理异常

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 "KeyboardInterrupt" exception.
可以编写处理所选异常的程序。请看下面的例子,它会要求用户一直输入,直到输入的是一个有效的整数,但允许用户中断程序(使用 "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...")
...
The "try" statement works as follows.
"try" 语句的工作原理如下。

• First, the try clause (the statement(s) between the "try" and "except" 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. Then if its type matches the exception named after the "except" keyword, the except clause is executed, and then execution continues after the "try" statement.
• 如果在执行try 子句时发生了异常,则跳过该子句中剩下的部分。然后,如果 异常的类型和 "except" 关键字后面的异常匹配,则执行 except 子句 ,然 后继续执行 "try" 语句之后的代码。

• 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. 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. An except clause may name multiple exceptions as a parenthesized tuple, for example:
一个 "try" 语句可能有多个 except 子句,以指定不同异常的处理程序。 最多会执行一个处理程序。 处理程序只处理相应的 try 子句中发生的异常,而不处理同一 "try" 语句内其他处理程序中的异常。 一个 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). For example, the following code will print B, C, D in that order:
如果发生的异常和 "except" 子句中的类是同一个类或者是它的基类,则异常和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")
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 子句被触发。

The last except clause may omit the exception name(s), to serve as a wildcard. 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):
最后的 except 子句可以省略异常名,以用作通配符。但请谨慎使用,因为以这种方式很容易掩盖真正的编程错误!它还可用于打印错误消息,然后重新引发异常(同样允许调用者处理异常):

   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:
print("Unexpected error:", sys.exc_info()[0])
raise
The "try" ... "except" statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:
"try" ... "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()
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. The variable is bound to an exception instance with the arguments stored in "instance.args". For convenience, the exception instance defines "__str__()" so the arguments can be printed directly without having to reference ".args". One may also instantiate an exception first before raising it and add any attributes to it as desired.
except 子句可以在异常名称后面指定一个变量。这个变量和一个异常实例绑定,它的参数存储在 "instance.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)
...

('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. For example:
异常处理程序不仅处理 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

8.4. Raising Exceptions

8.4. 抛出异常

The "raise" statement allows the programmer to force a specified exception to occur. For example:
"raise" 语句允许程序员强制发生指定的异常。例如:

   >>> raise NameError('HiThere') 
Traceback (most recent call last):
File "", line 1, in
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"). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:
"raise" 唯一的参数就是要抛出的异常。这个参数必须是一个异常实例或者是一个异常类(派生自 "Exception" 的类)。如果传递的是一个异常类,它将通过调用没有参数的构造函数来隐式实例化:

   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 "", line 2, in
NameError: HiThere

8.5. Exception Chaining

8.5. Exception Chaining

The "raise" statement allows an optional "from" which enables chaining exceptions by setting the "__cause__" attribute of the raised exception. For example:
The "raise" statement allows an optional "from" which enables chainingexceptions by setting the "__cause__" attribute of the raisedexception. For example:

   raise RuntimeError from OSError 
This can be useful when you are transforming exceptions. For example:
This can be useful when you are transforming exceptions. For example:

   >>> def func(): 
... raise IOError
...
>>> try:
... func()
... except IOError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "", line 2, in
File "", line 2, in func
OSError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "", line 4, in
RuntimeError
The expression following the "from" must be either an exception or "None". Exception chaining happens automatically when an exception is raised inside an exception handler or "finally" section. Exception chaining can be disabled by using "from None" idiom:
The expression following the "from" must be either an exception or"None". Exception chaining happens automatically when an exception israised inside an exception handler or "finally" section. Exceptionchaining can be disabled by using "from None" idiom:

>>> try:
...     open('database.sqlite') 
... except IOError:
...     raise RuntimeError from None 
... Traceback (most recent call last): File "", line 4, in RuntimeError
>>> try:
...     open('database.sqlite') 
... except IOError:
...     raise RuntimeError from None 
...Traceback (most recent call last):File "", line 4, in RuntimeError

8.6. User-defined Exceptions

8.6. 用户自定义异常

Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the "Exception" class, either directly or indirectly.
程序可以通过创建新的异常类来命名它们自己的异常(有关Python 类的更多信息,请参阅 类)。异常通常应该直接或间接地从 "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. When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:
可以定义异常类,它可以执行任何其他类可以执行的任何操作,但通常保持简单,通常只提供许多属性,这些属性允许处理程序为异常提取有关错误的信息。在创建可能引发多个不同错误的模块时,通常的做法是为该模块定义的异常创建基类,并为不同错误条件创建特定异常类的子类:

   class Error(Exception): 
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
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

8.7. 定义清理操作

The "try" statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:
"try" 语句有另一个可选子句,用于定义必须在所有情况下执行的清理操作。例如:

   >>> try: 
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
File "", line 2, in
KeyboardInterrupt
If a "finally" clause is present, the "finally" clause will execute as the last task before the "try" statement completes. The "finally" clause runs whether or not the "try" statement produces an exception. The following points discuss more complex cases when an exception occurs:
If a "finally" clause is present, the "finally" clause will execute asthe last task before the "try" statement completes. The "finally"clause runs whether or not the "try" statement produces an exception.The following points discuss more complex cases when an exceptionoccurs:

• If an exception occurs during execution of the "try" clause, the exception may be handled by an "except" clause. If the exception is not handled by an "except" clause, the exception is re-raised after the "finally" clause has been executed.
• If an exception occurs during execution of the "try" clause, theexception may be handled by an "except" clause. If the exception isnot handled by an "except" clause, the exception is re-raised afterthe "finally" clause has been executed.

• An exception could occur during execution of an "except" or "else" clause. Again, the exception is re-raised after the "finally" clause has been executed.
• An exception could occur during execution of an "except" or "else"clause. Again, the exception is re-raised after the "finally" clausehas been executed.

• If the "try" statement reaches a "break", "continue" or "return" statement, the "finally" clause will execute just prior to the "break", "continue" or "return" statement's execution.
• If the "try" statement reaches a "break", "continue" or "return"statement, the "finally" clause will execute just prior to the"break", "continue" or "return" statement's execution.

• If a "finally" clause includes a "return" statement, the "finally" clause's "return" statement will execute before, and instead of, the "return" statement in a "try" clause.
• If a "finally" clause includes a "return" statement, the "finally"clause's "return" statement will execute before, and instead of, the"return" statement in a "try" clause.

For example:
For example:

   >>> def bool_return(): 
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False
A more complicated example:
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 "", line 1, in
File "", 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. 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.
正如你所看到的,"finally" 子句在任何情况下都会被执行。 两个字符串相除所引发的 "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

8.8. 预定义的清理操作

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. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.
执行完语句后,即使在处理行时遇到问题,文件 *f* 也始终会被关闭。和文件一样,提供预定义清理操作的对象将在其文档中指出这一点。

results matching ""

    No results matching ""