该代码演示异常的作用是什么?

时间:2012-03-08 01:43:33

标签: python exception

我正在学习Python for Absolute Beginners这本书,并且是关于异常的章节。作者的解释越来越短,有了这段代码,我完全糊涂了,没有解释!有人可以逐行解释吗?

#!/usr/bin/env python
store = []
try: {}["foo"]
except KeyError as e: store.append(e)
try: 1/0
except ZeroDivisionError as e: store.append(e)
try: "".bar()
except AttributeError as e: store.append(e)
for exceptionobject in store:
    ec = exceptionobject.__class__
    print(ec.__name__)
    indent = " +-"
    while ec.__bases__:
        ec = ec.__bases__[0]
        print(indent + ec.__name__)
        indent = " " + indent

2 个答案:

答案 0 :(得分:4)

在上半部分(具有三个except子句的那个)它强制执行它捕获的异常(使用except关键字捕获异常),然后在异常处理程序中(代码)在关键字之后;它在发生异常时运行,或者引发)它将每个异常添加到列表中。

在下半部分,它会迭代已保存的异常(现在列表中的异常)并显示它们的一些属性。

在本练习中,你应该主要考虑如何捕获异常,其次只是异常是一个对象,就像Python中的所有东西一样:

In [6]: KeyError.__class__
Out[6]: type

'type'是Python中的类 - 这几乎是语言的一个怪癖,如果你没有得到它,你不应该很快就会担心它。无论如何,这一位表明异常是一个类。

In [7]: err = KeyError()
In [8]: err.__class__
Out[8]: KeyError

这里我们实例化一个KeyError对象,这是在发生KeyError异常时自动发生的(在这种情况下err与代码中的异常处理程序中的e相同)。正如您所看到的,err的课程符合预期KeyError

答案 1 :(得分:4)

# create a list
store = [] 

try:
    # if something in this block would throw an exception,
    # code could continue in a controlled way in an except block

    # force a KeyError by looking up a non-existent key in an empty dictionary
    {}["foo"] 

except KeyError as e: 
    # store the exception object in the list
    store.append(e)

# same scheme here; construct something that fails (1/0), 
# then instead of quitting the interpreter, continue operations
try: 
    1/0
except ZeroDivisionError as e: 
    store.append(e)

# pythons exceptions hierarchy is diverse and exceptions carry meaningful
# names expressing their context
try:
    # here we attept to lookup an attribute (that's happening technically
    # before the call), which does not exists (because strings don't know
    # how to bar... 
    "".bar()

except AttributeError as e:
    # ... and the the appropriate exception here is AttributeError
    store.append(e)

此时列表有三个元素,即异常对象。

# loop over list
for exceptionobject in store:

    # get the class of the object via special method __class__
    # __class__ returns an object whose class is type actually;
    # but don't be too confused by this 
    ec = exceptionobject.__class__

    # print the name of the exception class, now this is just a plain string
    print(ec.__name__)

    indent = " +-"

    # use another special method __bases__ to get all superclasses
    # of the exception class; all exceptions inherit from BaseException
    # loop over the base classes
    while ec.__bases__:

        # get the first base class
        ec = ec.__bases__[0]

        # print its name an indent more
        print(indent + ec.__name__)
        indent = " " + indent

结果应如下所示:

KeyError
 +-LookupError
  +-StandardError
   +-Exception
    +-BaseException
     +-object
ZeroDivisionError
 +-ArithmeticError
  +-StandardError
   +-Exception
    +-BaseException
     +-object
AttributeError
 +-StandardError
  +-Exception
   +-BaseException
    +-object

显示exception hierarchy的一部分。