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

后端 未结 5 795
囚心锁ツ
囚心锁ツ 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 08:51

    You can also use sys.exc_info(). exc_info() returns 3 values: type, value, traceback. On documentation: 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__
    
    0 讨论(0)
  • 2020-12-04 08:55

    Here are a few different ways to get the name of the class of the exception:

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

    e.g.,

    try:
        foo = bar
    except Exception as exception:
        assert type(exception).__name__ == 'NameError'
        assert exception.__class__.__name__ == 'NameError'
        assert exception.__class__.__qualname__ == 'NameError'
    
    0 讨论(0)
  • 2020-12-04 08:58

    If you want the fully qualified class name (e.g. sqlalchemy.exc.IntegrityError instead of just IntegrityError), you can use the function below, which I took from MB's awesome answer to another question (I just renamed some variables to suit my tastes):

    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__
    

    Example:

    try:
        # <do something with sqlalchemy that angers the database>
    except sqlalchemy.exc.SQLAlchemyError as e:
        print(get_full_class_name(e))
    
    # sqlalchemy.exc.IntegrityError
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-04 09:08

    The other answers here are great for exploration purposes, but if the primary goal is to log the exception (including the name of the exception), perhaps consider using logging.exception instead of print?

    0 讨论(0)
提交回复
热议问题