Home > front end >  Can I catch all exceptions by using try and catch in "__main__"
Can I catch all exceptions by using try and catch in "__main__"

Time:03-02

Is it possible too catch all exceptions if I use try except block in "main"? I tried catching the exception but I can't. I have attached exception image along with code

enter code here

if __name__ == '__main__':
  try:
     app = QtWidgets.QApplication(sys.argv)
     window = MainWindow()
     debug_file = "errors.txt"
     window.setWindowFlags(QtCore.Qt.WindowType.CustomizeWindowHint)
     window.show()
     ret = app.exec_()
     [enter image description here][1]sys.exit()

except KeyboardInterrupt:
    print("Theres an exception")
    traceback_str = "".join(traceback.format_exc())
    with open("errors.txt", "a") as log:
        log.write(datetime.now().isoformat()   "\n")
        log.write(traceback_str   "\n")
        print(traceback_str)
except  AttributeError:
    print("Theres an exception")
    traceback_str ="".join(traceback.format_exc())
    with open("errors.txt","a") as log:
        log.write(datetime.now().isoformat() "\n")
        log.write(traceback_str  "\n")
        print(traceback_str)

CodePudding user response:

As explained here, you can create an exception handler and monkey patch sys.excepthook:

import sys
import logging

logger = logging.getLogger(__name__)

def handle_unhandled_exception(e_type, e_value, e_traceback):
    logger.critical("Unhandled exception", exc_info=(e_type, e_value, e_traceback))
    do_other_stuff_at_your_convenience()

sys.excepthook = handle_unhandled_exception
  • Related