# 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的一部分。