获取异常对象所属的类的名称:
e.__class__.__name__
并且使用print_exc()函数还将打印堆栈跟踪,这对于任何错误消息都是必不可少的信息。
像这样:
from traceback import print_exc
class CustomException(Exception): pass
try:
    raise CustomException("hi")
except Exception, e:
    print 'type is:', e.__class__.__name__
    print_exc()
    # print "exception happened!"
您将获得如下输出:
type is: CustomException
Traceback (most recent call last):
  File "exc.py", line 7, in <module>
    raise CustomException("hi")
CustomException: hi
在打印和分析之后,代码可以决定不处理异常,而只是执行raise:
from traceback import print_exc
class CustomException(Exception): pass
def calculate():
    raise CustomException("hi")
try:
    calculate()
except Exception, e:
    if e.__class__ == CustomException:
        print 'special case of', e.__class__.__name__, 'not interfering'
        raise
    print "handling exception"
输出:
special case of CustomException not interfering
解释器输出异常:
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    calculate()
  File "test.py", line 6, in calculate
    raise CustomException("hi")
__main__.CustomException: hi
经过raise最初的异常继续进一步传播调用堆栈。(当心可能的陷阱)如果引发新的异常,它将产生新的(较短的)堆栈跟踪。
from traceback import print_exc
class CustomException(Exception): pass
def calculate():
    raise CustomException("hi")
try:
    calculate()
except Exception, e:
    if e.__class__ == CustomException:
        print 'special case of', e.__class__.__name__, 'not interfering'
        #raise CustomException(e.message)
        raise e
    print "handling exception"
输出:
special case of CustomException not interfering
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    raise CustomException(e.message)
__main__.CustomException: hi    
请注意,traceback如何不包括calculate()来自9作为原始异常源的line函数e。
               
              
except:(无裸raise),除了也许一旦每个程序,并且优选地不然后。