How to get the name of an exception that was caught in Python?

后端 未结 5 797
囚心锁ツ
囚心锁ツ 2020-12-04 08:26

How can I get the name of an exception that was raised in Python?

e.g.,

try:
    foo = bar
except Exception as exception:
    name_of_exception = ???         


        
5条回答
  •  抹茶落季
    2020-12-04 09:06

    This works, but it seems like there must be an easier, more direct way?

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

提交回复
热议问题