2010-02-17 24 views
4

SwingUtilities.invokeAndWait()拋出InterruptedExceptionInvocationTargetException我該如何處理這些?SwingUtilities.invokeAndWait拋出的異常應該怎麼做?

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

我想使用的方法來顯示一個對話框,並等待用戶說yes或no。據我所知InvocationTargetException意味着有一個RuntimeException,我可以這樣對待它。然而,我想爲InterruptedException真正想要的是忽略它,並讓線程繼續,直到用戶給出答案。

回答

2

InterruptedException在這個article解釋。

InvocationTargetException,如果Runnables run方法拋出異常,則拋出它。

也許運行這個例子闡明事情:

 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); 
    } 
+1

'InterruptedException'意味着*調用線程被中斷,而不是EDT。 – finnw 2010-02-17 11:59:04

+0

這是否意味着賦給'invokeAndWait'的'Runnable'不會被執行? – Thirler 2010-02-17 12:48:36

+0

文章鏈接已死亡。 – 2013-11-02 03:13:12

1

顯示對話框時發生InterruptedException異常極其罕見。您可以忽略它,或者再次嘗試通過在新的Runnable上調用invokeAndWait來顯示對話框。

如果對話框被單獨調用(即不作爲主GUI的一部分),使用invokeAndWait就沒有問題。但是,如果您在EDT中顯示對話框,則可能不想使用invokeAndWait。更多細節在這裏:Concurrency in Swing

+0

這是部分答案。假設我想從工作線程#1中顯示對話框,然後調用invokeAndWait。然後,如果工作線程#2進來並告訴系統對話不再需要,那麼該線程會中斷工作線程#1,因此現在需要處理由invokeAndWait拋出的InterruptedException。例如,我所做的就是捕捉異常,將對話框(在invokeLater上,這次)處理掉,然後向上拋出異常。所以這個用例是完全有效的,而且非常乾淨。我不同意你的第一句話。 – Timmos 2016-02-10 15:06:28