import traceback import sys class PrintExceptionAtExit(object): def __init__(self): try: x = 1 / 0 except Exception as e: self.e = sys.exc_info() # self.e.__traceback__ contains frames: explicitly clear the # reference to self in the current frame to break a reference cycle self = None def __del__(self): traceback.print_exception(*self.e) a = PrintExceptionAtExit()