views:

147

answers:

2

SwingUtilities.invokeAndWait() throws an InterruptedException and an InvocationTargetException how should I handle these?

 public static void invokeAndWait(Runnable doRun) throws InterruptedException,
                                 InvocationTargetException

I want to use the method to show a dialog and wait for the user to say yes or no. As far as I can tell the InvocationTargetException means there was a RuntimeException and I can treat it like that. However what I would really want for the InterruptedException is to ignore it and have thread continue until the user has given an answer.

+1  A: 

An InterruptedException while showing a dialog box would be extremely rare. You could ignore it, or try displaying the dialog again by calling invokeAndWait on a new Runnable again.

If the dialog is being called as standalone (i.e. not as part of the main GUI), using invokeAndWait is fine. However if you are displaying the dialog from within the EDT, you might not want to use invokeAndWait. More details here: Concurrency in Swing

Luhar
+2  A: 

InterruptedException is explained in this article.

The InvocationTargetException, it's thrown if the Runnables run method throws an exception.

Maybe running this example clarifies things:

        try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                System.out.println("1");
                if (true) {
                    throw new RuntimeException("runtime exception");
                }
                System.out.println("2");
            }
        });
    } catch (InterruptedException e) {
        e.printStackTrace(System.out);
    } catch (InvocationTargetException e) {
        e.printStackTrace(System.out);
    }
fulkod
An `InterruptedException` means the *calling* thread was interrupted, not the EDT.
finnw
Does this mean that the `Runnable` given to 'invokeAndWait' doesn't get executed anymore?
Thirler