执行过程中检测到的错误称为异常,并非无条件致命。大多数异常不会被程序处理,但可以编写处理选定异常的程序。Python 有专门的功能来处理异常和异常逻辑。此外,异常有丰富的类型层次结构,所有异常都继承自 BaseException 类型。

Section 88.1: 捕捉异常

使用 try...except: 捕捉异常。应尽可能精确地指定异常:

try:
  x = 5 / 0
except ZeroDivisionError as e:
  # `e` is the exception object
  print("Got a divide by zero! The exception was:", e)
  # handle exceptional case
  x = 0
finally:
  print("The END")
  # it runs no matter what execute.

捕捉异常

指定的异常类(本例中为 ZeroDivisionError 类)会捕获属于该类或该异常的任何子类的任何异常。

例如,ZeroDivisionError 是 ArithmeticError 的子类:

>>> ZeroDivisionError.__bases__
(<class 'ArithmeticError'>,)

因此,下面的代码仍然会捕捉到 ZeroDivisionError:

try:
  5 / 0
except ArithmeticError:
  print("Got arithmetic error")

捕捉异常

Section 88.2: 不要什么都抓!

虽然捕获每一个Exception都很有诱惑力:

try:
  very_difficult_function()
except Exception:
  # log / try to reconnect / exit gratiously
finally:
  print "The END"
  # it runs no matter what execute.

甚至是一切(包括 BaseException 及其所有子类,包括 Exception ):

try:
  even_more_difficult_function()
except:
  pass # do whatever needed

在大多数情况下,这是一种糟糕的做法。它可能会捕捉到比预期更多的错误,如 SystemExit、KeyboardInterrupt 和 MemoryError--每种错误的处理方式通常都应不同于通常的系统或逻辑错误。这也意味着,对于内部代码可能会做错什么,以及如何从这种情况下正确恢复,没有一个清晰的认识。如果您捕捉到每一个错误,您就不会知道发生了什么错误或如何修复。

这种情况通常被称为 'bug masking' ,应该避免。让程序崩溃,而不是无声无息地失败,或者更糟糕的是,在更深的执行层次上失败。(想象一下这是一个事务系统)

通常,这些结构会在程序的最外层使用,并记录错误的细节,以便修复错误或更有针对性地处理错误。

Section 88.3: 再次加注的例外情况

有时,您想捕获一个异常来检查它,例如为了记录日志。检查结束后,您希望异常继续像以前一样传播。

在这种情况下,只需使用不带参数的 raise 语句即可。

try:
  5 / 0
except ZeroDivisionError:
  print("Got an error")
  raise

再次加注的例外情况

不过请记住,在调用者堆栈中更高一级的调用者仍然可以捕获异常并以某种方式进行处理。在这种情况下,“已完成输出 ”可能会带来麻烦,因为它在任何情况下(捕获或未捕获)都会发生。因此,更好的办法可能是引发另一个异常,其中包含您对这种情况的评论以及原始异常:

try:
  5 / 0
except ZeroDivisionError as e:
  raise ZeroDivisionError("Got an error", e)

再次加注的例外情况

但这样做的缺点是会将异常跟踪缩减为这个 raise,而不带参数的 raise 会保留原来的异常跟踪。

在 Python 3 中,使用 raise-from 语法可以保留原始堆栈:

raise ZeroDivisionError("Got an error") from e

Section 88.4: 捕获多个异常

有几种方法可以 “捕获多个异常”。

第一种方法是创建一个由希望捕获的异常类型组成的元组,并以相同的方式进行处理。此示例将使代码忽略 KeyError 和 AttributeError 异常。

try:
  d = {}
  a = d[1]
  b = d.non_existing_field
except (KeyError, AttributeError) as e:
  print("A KeyError or an AttributeError exception has been caught.")

捕获多个异常

如果希望以不同的方式处理不同的异常,可以为每种类型提供一个单独的异常块。在本例中,我们仍会捕获 KeyError 和 AttributeError,但会以不同的方式处理异常。

try:
  d = {}
  a = d[1]
  b = d.non_existing_field
except KeyError as e:
  print("A KeyError has occurred. Exception message:", e)
except AttributeError as e:
  print("An AttributeError has occurred. Exception message:", e)

捕获多个异常

Section 88.5: 异常层次结构

异常处理基于异常层次结构进行,该层次结构由异常类的继承结构决定。

例如,IOError 和 OSError 都是 EnvironmentError 的子类。捕获 IOError 的代码不会捕获 OSError。但是,捕获 EnvironmentError 的代码将同时捕获 IOError 和 OSError。

内置异常的层次结构:

Python 3.x Version ≥ 3.0

BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning

Section 88.6: Else

只有当 “try ”代码块中的代码没有引发异常时,else 代码块中的代码才会被运行。如果您有一些代码不想在抛出异常时运行,但又不想捕获由该代码抛出的异常,这就很有用。

例如

try:
  data = {1: 'one', 2: 'two'}
  print(data[1])
except KeyError as e:
  print('key not found')
else:
  raise ValueError()
# Output: one
# Output: ValueError

Else

请注意,这种 else: 不能与 elif 的 else 子句开始的 if 结合使用。如果您有下面的 if,它需要缩进到else:下面:

try:
  ...
except ...:
  ...
else:
  if ...:
    ...
  elif ...:
    ...
  else:
    ...

Section 88.7: 引发异常

如果代码遇到不知道如何处理的情况,例如参数不正确,就应该引发相应的异常。

def even_the_odds(odds):
  if odds % 2 != 1:
    raise ValueError("Did not get an odd number")
  return odds + 1

引发异常

Section 88.8: 创建自定义异常类型

创建一个继承自 Exception 的类:

class FooException(Exception):
  pass

try:
  raise FooException("insert description here")
except FooException:
  print("A FooException was raised.")

创建自定义异常类型

或其他异常类型:

class NegativeError(ValueError):
  pass

def foo(x):
  # function that only accepts positive values of x
  if x < 0:
    raise NegativeError("Cannot process negative numbers")
    ... # rest of function body
try:
  result = foo(int(input("Enter a positive integer: "))) # raw_input in Python 2.x
except NegativeError:
  print("You entered a negative number!")
else:
  print("The result was " + str(result))

Section 88.9: 异常处理实例

用户输入

想象一下,您希望用户通过 input 输入一个数字。您要确保输入的是一个数字。为此,您可以使用 try/except:

while True:
  try:
    nb = int(input('Enter a number: '))
    break
  except ValueError:
    print('This is not a number, try again.')

异常处理实例

注意:Python 2.x 将使用 raw_input 代替;函数 input 存在于 Python 2.x,但语义不同。在上面的示例中,input 也接受诸如 2 + 2 这样的表达式,这些表达式的值是一个数字。

如果输入不能转换为整数,就会引发 ValueError。你可以用 except 来捕获它。如果没有异常,break会跳出循环。循环结束后,nb 包含一个整数。

字典

想象一下,你正在迭代一个连续整数的列表,比如 range(n),你有一个字典 d 列表,其中包含遇到某些特定整数时要做的事情的信息,比如跳过 d[i] 下一个整数。

d = [{7: 3}, {25: 9}, {38: 5}]

for i in range(len(d)):
  do_stuff(i)
  try:
    dic = d[i]
    i += dic[i]
  except KeyError:
    i += 1

如果您试图从字典中获取一个不存在的键的值,则会引发 “KeyError”。

Section 88.10: 异常也是对象

异常只是从内置的 BaseException 继承而来的普通 Python 对象。Python 脚本可以使用 raise 语句来中断执行,使 Python 打印调用堆栈的堆栈跟踪和异常实例的表示。例如

>>> def failing_function():
...     raise ValueError('Example error!')
>>> failing_function()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in failing_function
ValueError: Example error!

异常也是对象

它说一个ValueError消息是Example error! 是由我们的failing_function()引发的,它在解释器中执行。

调用代码可以选择处理调用可能引发的任何和所有类型的异常:

>>> try:
...     failing_function()
... except ValueError:
...     print('Handled the error')
Handled the error

异常也是对象

您可以通过在异常处理代码的 “except... ”部分分配异常对象来获取异常对象:

>>> try:
...   failing_function()
... except ValueError as e:
...   print('Caught exception', repr(e))
Caught exception ValueError('Example error!',)

异常也是对象

Python 内置异常的完整列表及其描述可在 Python 文档:https://docs.python.org/3.5/library/exceptions.html 中找到。下面是按层次排列的完整列表: 异常层次结构。

Section 88.11: 使用 finally 运行清理代码

有时,您可能希望不管发生了什么异常都能发生某些事情,例如,如果您必须清理某些资源的话。

无论是否出现异常,try 子句的 finally 块都会发生。

resource = allocate_some_expensive_resource()
try:
  do_stuff(resource)
except SomeException as e:
  log_error(e)
  raise # re-raise the error
finally:
  free_expensive_resource(resource)

使用上下文管理器(使用 with 语句)处理这种模式通常效果更好。

Section 88.12: 异常链与raise from

在处理异常的过程中,您可能希望引发另一个异常。例如,如果您在从文件读取数据时收到一个 IOError,您可能想引发一个特定于应用程序的错误,而不是向您的库的用户展示。

您可以用异常链来显示异常的处理过程:

>>> try:
  5 / 0
except ZeroDivisionError as e:
  raise ValueError("Division failed") from e

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

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

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

异常链与raise from