Search code examples
pythonwxpython

Difference between raising exception and automatically causing an exception


Currently using the wxPython framework and my code looks like this:

Event bind:

self.frequency_grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.on_cell_changed)

Function that handles changed cells:

def on_cell_changed(self, event):
    self.current_grid = event.GetEventObject()
    try:
        new_value= self.get_cell_value()
        if new_value < 0:
            raise AttributeError
        #allow the cell to update
    except AttributeError:
        event.Veto()
        wx.MessageBox(_("Positive values only."), "", wx.OK|wx.ICON_WARNING)
    except:
        wx.MessageBox(_("Invalid value for cell."), "", wx.OK|wx.ICON_WARNING)
        event.Veto()

The function get_cell_value() reads the value from the current cell and converts it to an integer simply by using int(). If the user enters a character like 'a' into the cell, obviously this function fails and the exception is raised. In this case the messagebox comes out telling the user the cell has an invalid value. This is what I call the automatically caused exception, and the final exception block is executed.

In the case of negative values, I manually raise an AttributeError (just wanted to see something different from ValueError which is what happens when user inputs characters). In this case however, the wxPython sends the EVT_GRID_CELL_CHANGE event twice, so there must be something different about manually raised exceptions.

I've separately raised a ticket about the duplicated events at http://trac.wxwidgets.org/ticket/16333 but just trying to understand how the first scenario doesn't make wxPython send 2 events compared to the second scenario.


Solution

  • After a bit more tracing, I found that creating the MessageBox causes the EVT_GRID_CELL_CHANGING event to occur, which then leads to the EVT_GRID_CELL_CHANGED event to occur, which is why I saw duplicated events. The reason why I did not see duplicated events during the entry of a character was because a Veto() was called in the event handler for the EVT_GRID_CELL_CHANGING if an int() conversion was invalid because my handler for that event gets the grid input and tries to convert it.

    In conclusion, there is no difference in Python exception handling, but however, a better wxPython demo should be implemented to prevent the duplicated message box during the demo and show other users how to better use the grid mechanism.