Alex Rivera | Logout

How should I handle exceptions when using SwingWorker?

Asked 2009-04-26T17:16:05.390
24

I use SwingWorker in Java 6 to avoid running long-running code on the event dispatch thread.

If the call to get() in my done() method returns an exception, what is an appropriate way of handling the exception?

I'm particularly concerned about possible InterruptedExceptions. The JavaDoc example simply ignores the exception but I've learnt over the years that swallowing exceptions leads to hard-to-debug code.

A sample usage is as follows:

new SwingWorker<String, Void>() {

    @Override
    protected String doInBackground() throws Exception {
        // do long-running calculation
        return result;
    }

    @Override
    protected void done() {
        try {
            setTextField(get());
        } catch (InterruptedException e) {
            e.printStackTrace();  
        } catch (ExecutionException e) {
            e.printStackTrace();  
        }
    }
}.execute();
Edit
Report

1 Answer

-2

I guess you don't get many of these question with C#. You need to understand what the exception is and deal with it appropriately (which is usually to let it go further up the stack).

InterruptedException - Thrown when a thread is interrupted (by Thread.interrupt) when waiting (roughly). Why would you want a thread to be interrupted? Usually you want the thread to stop what it's doing - reset the interrupt state and exit. For instance, the PlugIn will interrupt applet threads if they continue for much longer after an applet should be gone. However, in this case provided done is called correctly you shouldn't be waiting at all. Therefore, it would be appropriate to wrap the exception in an IllegalStateException (and the API docs should probably state that). It's a really bad API. The publish/process mode probably makes more sense.

ExecutionException - You need to deal with the wrapped exception. If you are not expecting a particular type of exception, wrap it in an unchecked exception.

Generally I would suggest a clear separation between what happens on the EDT and what happens off the EDT. Therefore, avoid SwingWorker in production code.

answered 2009-04-26T19:07:09.883

Your Answer