0

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)
Paul Jose
  • 13
  • 4
  • Does this answer your question? [How can I write a \`try\`/\`except\` block that catches all exceptions?](https://stackoverflow.com/questions/4990718/how-can-i-write-a-try-except-block-that-catches-all-exceptions) – 001 Mar 01 '22 at 15:01
  • I tried to do that but no matter what I cannot catch this exception. THis is why I tried catching specifically the Attribute error. Thank you for the reply @JohnnyMopp – Paul Jose Mar 01 '22 at 15:09
  • Ok. Looking more closely, maybe this: [Catching exceptions raised in QApplication](https://stackoverflow.com/q/55819330) – 001 Mar 01 '22 at 15:18
  • Hey @JohnnyMopp. The thread you shared worked I used the excepthook and it is working now as I want it to. Thank you for the help – Paul Jose Mar 02 '22 at 10:32

1 Answers1

0

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
aerobiomat
  • 2,883
  • 1
  • 16
  • 19