Uncaught exceptions in GUI applications
In our discussion of uncaught exception handlers in Java,
we noted that the general behaviour is for a thread to be terminated (and the uncaught
exception handler invoked) when an uncaught exception occurs.
In practical terms, an exception to this is in GUI applications (including Swing
applications), where an uncaught exceptions occurs in the event dispatch thread. This means
in event handlers, such as the actionPerformed() method of an
ActionListener. In such cases:
- we generally wouldn't want the event dispatch thread to die
(and so the GUI to stop working) just because of a single badly-behaved event handler;
- but we probably would want the exception handler to be called, as we might
have important logging code in there, for example.
So what happens is that the event dispatch thread is allowed to die as normal, and
a new event dispatch thread is started to replace the one that died. This
gives us the "best of both worlds": we still get to carry out our logging/processing
of the exception as usual, but the GUI carries on working.
Effect of an uncaught exception on future event handlers
Note, however, that an uncaught exception will prevent the event from being
passed to other listeners. For example, in this code:
handler1 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ...
}
};
handler2 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = null;
int len = str.length();
}
};
JButton b = ...
b.addActionListener(handler1);
b.addActionListener(handler2);
when the button is clicked, handler2 will be called first. The second
lline of handler2's actionPerformed() method causes an uncaught
NullPointerException to be thrown. The event dispatch thread dies (and
is recreated), and handler1's actionPerformed() method is never
called for that button click. (Note the implementational detail that event handlers
are called in reverse order to the order they were registered.)
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.