Why decorator-style context manager in Python doesn't catch exception within Tkinter window? -
there simple code decorator-generated context manager via contextlib. when press button exception raised , not handled context manager. why it?
from tkinter import tk, button contextlib import contextmanager def close_window(): window.destroy() raise exception @contextmanager def safe(): try: yield except: print 'exception catched' safe(): window = tk() button = button(window, text='press me', command=close_window) button.pack() window.mainloop()
why exception still raise?
upd use python 2.7
the tkinter main process loop not brought down exceptions , not propagate them further. hence, exception never reaches till with
statement (since tkinter catches , reports exception , stops execution).
you need create decorator catch exception , log them or whatever logic want do.
example -
from tkinter import tk, button contextlib import contextmanager class exceptioncatcher: # <---the decorator def __init__(self, function): self.function = function def __call__(self, *args, **kwargs): try: return self.function(*args, **kwargs) except exception: print 'exception catched1' @exceptioncatcher def close_window(): window.destroy() raise exception @contextmanager def safe(): try: yield except exception: print 'exception catched' safe(): window = tk() button = button(window, text='press me', command=close_window) button.pack() window.mainloop()
with above code, when click on press
button, logs exception catched1
me , exits.
also, not except:
should give exception want catch (or atleast except exception:
).
Comments
Post a Comment