如何获取在Python中被捕获的exception的名称?

我怎样才能得到在Python中引发的exception的名称?

例如,

try: foo = bar except Exception as exception: name_of_exception = ??? assert name_of_exception == 'NameError' print "Failed with exception [%s]" % name_of_exception 

例如,我捕获多个(或全部)exception,并希望在错误消息中打印exception的名称。

以下是获取exception名称的两种不同方式:

  1. type(exception).__name__
  2. exception.__class__.__name__

例如,

 try: foo = bar except Exception as exception: assert type(exception).__name__ == 'NameError' assert exception.__class__.__name__ == 'NameError' 

这有效,但似乎必须有一个更简单,更直接的方式?

 try: foo = bar except Exception as exception: assert repr(exception) == '''NameError("name 'bar' is not defined",)''' name = repr(exception).split('(')[0] assert name == 'NameError'