Reputation: 251
we observe strange painting behaviour when an exception in uncaught in a swing listener like this:
mytable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
... no try catch and npe exception happens
}
});
is it because we're throwing in swing and interrupt normal paint/updates? In window that throws we begin to see buttons in weird places, scroll bars appear multiple times. If so what to do? try/catch on every swing listener?
Upvotes: 0
Views: 63
Reputation: 688
By default, Swing doesn't do a particularly good job of handling unexpected exceptions. As you guessed, Swing clearly is not recovering cleanly in your particular situation.
Given that bugs happen, I prefer to provide an exception handler which displays a dialog to the user. This dialog ideally would have a "Report Bug" button that will allow the user to email the stack trace back to you so that you can fix the problem. The dialog should also allow the user to just ignore the problem and continue. When the dialog is closed you should just return normally which should leave the AWT event queue unaffected.
This type of dialog is useful not only for your users but also for anyone working on the code. Developers will run into crashes more frequently than users, and it is very helpful to have a dialog where the developer can choose to investigate the crash or just ignore it.
See this related thread which describes how to set up an exception handler:
How can I catch AWT thread exceptions in Java?
Upvotes: 0
Reputation: 691645
The reason of the strange painting is indeed the exception thrown by the listener. The solution is to avoid exceptions in listeners.
Embedding every listener code inside a try/catch block is not the solution, though. The solution is to avoid bugs, and fix them when they appear. The strange painting, along with the stack trace of the exception, is what allows you to detect when you have a bug in your listener code. A NullPointerException should never happen. If it happens, you have a bug. Catching the exception and swallowing it will only make the bug worse, because it will be undetected and will, for example, cause the display of wrong information to the user, which could make a disastrous action based on this wrong information.
Upvotes: 1