How to save traceback / sys.exc_info() values in a variable?

前端 未结 5 1322
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 05:33

I want to save the name of the error and the traceback details into a variable. Here\'s is my attempt.

import sys
try:
    try:
        print x
    except E         


        
5条回答
  •  醉话见心
    2020-12-02 06:27

    sys.exc_info() returns a tuple with three values (type, value, traceback).

    1. Here type gets the exception type of the Exception being handled
    2. value is the arguments that are being passed to constructor of exception class
    3. traceback contains the stack information like where the exception occurred etc.

    For Example, In the following program

    try:
    
        a = 1/0
    
    except Exception,e:
    
        exc_tuple = sys.exc_info()
    

    Now If we print the tuple the values will be this.

    1. exc_tuple[0] value will be "ZeroDivisionError"
    2. exc_tuple[1] value will be "integer division or modulo by zero" (String passed as parameter to the exception class)
    3. exc_tuple[2] value will be "trackback object at (some memory address)"

    The above details can also be fetched by simply printing the exception in string format.

    print str(e)
    

提交回复
热议问题