Friday, October 09, 2015

Exception handling in Thread and SwingWorker

Exception handling in SwingWorker differs from Thread. When using a Thread if an exception is thrown inside run(), it is propagated up the chain and you can handle it outside if you want. When an exception occurs in SwingWorker.doInBackground(), you have to handle it in the done() method. The following code demonstrates this. If you delete the done() method, it will run but the exception will be lost.
/**
 * Demonstrates difference of SwingWorker and Thread when an exception occurs. In SwingWorker, if you don't catch the exception in done(), it gets lost.
 */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Thread.run");
            throw new IllegalArgumentException();
        }
    }).start();

    new SwingWorker() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("SwingWorker.doInBackground");
            if (true) {
                throw new IllegalArgumentException();
            }
            return null;
        }
        @Override
        protected void done() {
            try {
                get();
            } catch (InterruptedException e) {
                System.out.println("Caught exception: " + e);
            } catch (ExecutionException e) {
                System.out.println("Caught exception: " + e);
            }
        }
    }.execute();
}

Output:
For more information see How should I handle exceptions when using SwingWorker?

No comments: