Exception hooks

In wxPython, it's possible to handle uncaught exceptions with an exception hook. Wax makes this especially easy: in a given frame, define or override the __ExceptHook__ method. (Usually you'll want to use the root frame for this.)

The __ExceptHook__ method must be defined with three parameters (besides self):

class MyFrame(Frame):
    def __ExceptHook__(self, exctype, value, traceback):
        ...handle exception...

If the root frame has an __ExceptHook__ method, then it will be assigned to sys.excepthook when the application is initialized. If you use other code or libraries that set sys.excepthook as well, this may cause a conflict.

Using __ExceptHook__ to write a simple handler

The following example demonstrates how to use this method.

# excepthook-1.py

from wax import *

class MainFrame(Frame):
    def Body(self):
        b = Button(self, "Generate exception", event=self.OnButtonClick)
        self.AddComponent(b, expand='both', border=5)
        self.Pack()
        self.Size = 100, 100
    def OnButtonClick(self, event):
        print 1/0
    def __ExceptHook__(self, exctype, value, traceback):
        print "The following exception was caught:"
        print "exctype:", exctype
        print "value:", value
        print "traceback:", traceback

app = Application(MainFrame)
app.Run()

When the button is clicked, it produces output similar to the following:

The following exception was caught:
exctype: exceptions.ZeroDivisionError
value: integer division or modulo by zero
traceback: <traceback object at 0x0191A3A0>

Writing a more user-friendly handler using ErrorDialog

The ErrorDialog widget (defined in tools/errordialog.py) was designed to cooperate with __ExceptHook__ and handle uncaught exceptions gracefully. Here's how to use it:

# excepthook-2.py

from wax import *
from wax.tools.errordialog import ErrorDialog

class MainFrame(Frame):
    def Body(self):
        b = Button(self, "Generate exception", event=self.OnButtonClick)
        self.AddComponent(b, expand='both', border=5)
        self.Pack()
        self.Size = 100, 100
    def OnButtonClick(self, event):
        print 1/0
    def __ExceptHook__(self, exctype, value, traceback):
        dlg = ErrorDialog(self, exctype, value, traceback)
        dlg.ShowModal()
        dlg.Destroy()

app = Application(MainFrame)
app.Run()

Clicking the button will generate an exception, which will cause the handler to produce this dialog: