Archive for March, 2009

h1

Catching all Runtime Exceptions in Swing

March 30, 2009

[note: see my post about writing a java thick client applications using extjs]

So you got some framework that you are using in your swing application and it throws a runtime exception. The Exception is thrown all the way out and ends up on the system.out – very nasty, not good looking and doesn’t help us determining that there is a problem in our application. We might just go on and do the same task again even though the exception was telling us that something went fatally wrong and that it probably would be a good idea to change the state of the application, go into recovery or terminate gracefully.

What can we do to prevent this? We can use try/catch clauses all over the place whenever we call some third party code but that is neither fun nor good code. And still there can be some exceptions slipping by – or are you really sure your code never throws a null pointer exception? Really?

There is an easier way to deal with this problem: All swing activity originates from the event queue and therefore all events are thrown to the event queue as well.  So in order to catch all runtime exceptions such as a null pointer exception we can just use the event queue.

We just need to extend EventQueue and overwrite the dispatchEvent method.

class EventQueueProxy extends EventQueue {

	protected void dispatchEvent(AWTEvent newEvent) {
		try {
			super.dispatchEvent(newEvent);
		} catch (Throwable t) {
			t.printStackTrace();
			String message = t.getMessage();

			if (message == null || message.length() == 0) {
				message = "Fatal: " + t.getClass();
			}

			JOptionPane.showMessageDialog(null, "General Error", message, JOptionPane.ERROR_MESSAGE);
		}
	}
}

The proxy class still calls it’s parents dispatchEvent method and catches anything throwable. When it does, it pops up a simple dialog.

Only thing remaining, we need to install our new event dispatcher on the event queue.

EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
queue.push(new EventQueueProxy());

Using this method one can also use exceptions to handle errors throughout a swing application – dealing with errors and exceptions ends up at one place in the application this way and can be used to transform the exceptions into human readable error messages.

For some other helpful links for building swing applications have a look at helpful-java-swing-articles

Advertisements