如何获取在Python中引发的异常的名称?

例如,

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

例如,我正在捕获多个(或所有)异常,并希望在错误消息中打印异常的名称。


当前回答

这是可行的,但似乎一定有更简单、更直接的方法?

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

其他回答

如果你想要完全限定的类名(例如sqlalchemy. exx .IntegrityError而不仅仅是IntegrityError),你可以使用下面的函数,这是我从MB对另一个问题的出色回答中获得的(我只是重命名了一些变量以适应我的口味):

def get_full_class_name(obj):
    module = obj.__class__.__module__
    if module is None or module == str.__class__.__module__:
        return obj.__class__.__name__
    return module + '.' + obj.__class__.__name__

例子:

try:
    # <do something with sqlalchemy that angers the database>
except sqlalchemy.exc.SQLAlchemyError as e:
    print(get_full_class_name(e))

# sqlalchemy.exc.IntegrityError

你可以使用一些格式化字符串打印异常:

例子:

try:
    #Code to execute
except Exception as err:
    print(f"{type(err).__name__} was raised: {err}")

你也可以使用sys.exc_info()。Exc_info()返回3个值:类型,值,回溯。关于文档:https://docs.python.org/3/library/sys.html#sys.exc_info

import sys

try:
    foo = bar
except Exception:
    exc_type, value, traceback = sys.exc_info()
    assert exc_type.__name__ == 'NameError'
    print "Failed with exception [%s]" % exc_type.__name__

这里的其他答案非常适合探究目的,但如果主要目标是记录异常(包括异常的名称),也许可以考虑使用日志记录。异常而不是打印?

这是可行的,但似乎一定有更简单、更直接的方法?

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