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()