0

Let's look at this simple tkinter application: i use report_callback_exception to handle the exceptions but it works only in the main thread. How can i catch all the exceptions, included the exceptions raised in a thread, and report them on the main thread with the method exception_handler?

import threading
import tkinter
import tkinter.messagebox
import traceback


class App(tkinter.Tk):
    def __init__(self):
        super(App, self).__init__()

        tkinter.Button(self, text="Exception", command=self.raise_exception).pack()
        tkinter.Button(self, text="Threaded exception", command=self.raise_threaded_exception).pack()

        self.report_callback_exception = self.exception_handler

    def exception_handler(self, *args):
        error_message = "".join(traceback.format_exception(*args))
        tkinter.messagebox.showerror(parent=self, title="Error", message=error_message)

    @staticmethod
    def raise_exception():
        raise Exception("Hello, handled error!")

    @staticmethod
    def raise_threaded_exception():
        def execute():
            raise Exception("Hello, unhandled error!")

        thread = threading.Thread(target=execute, daemon=True)
        thread.start()


if __name__ == "__main__":
    app = App()
    app.mainloop()

Funpy97
  • 282
  • 2
  • 9
  • Does this answer your question? [Catch a thread's exception in the caller thread?](https://stackoverflow.com/questions/2829329/catch-a-threads-exception-in-the-caller-thread) – relent95 Dec 03 '22 at 04:53
  • I don't recommend to use an undocumented method ``report_callback_exception()``` and doing a monkey patch on it. – relent95 Dec 03 '22 at 04:58

0 Answers0