pythonpython-2.7exceptionstack-trace

Get exception description and stack trace which caused an exception, all as a string


How to convert a caught Exception (its description and stack trace) into a str for external use?

try:
    method_that_can_raise_an_exception(params)
except Exception as e:
    print(complete_exception_description(e))

Solution

  • See the traceback module, specifically the format_exc() function. Here.

    import traceback
    
    try:
        raise ValueError
    except ValueError:
        tb = traceback.format_exc()
    else:
        tb = "No error"
    finally:
        print(tb)