2011-07-01 51 views
2
InputStream in = ClientSocket.getInputStream(); 
new Thread() 
{ 
    public void run() { 
     while (true) 
     { 
      int i = in.read(); 
      handleInput(i); 
     } 
    } 
}.start(); 

我在聽新的數據套接字上使用此代碼,並獲得:如何在匿名線程中聲明異常?

FaceNetChat.java:37: unreported exception java.io.IOException; must be caught or declared to be thrown 
       int i = in.read(); 
          ^

當我添加 「拋出IOException異常」 後 「的run()」 我得到:

FaceNetChat.java:34: run() in cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException 
     public void run() throws IOException { 
        ^

這可能很簡單,但我很茫然。我如何通過這個?

+0

您希望程序如何處理異常? – skaffman

+0

@SomeBloke,實現一個Runnable並將其傳遞給Thread是最佳實踐,而不是對Thread進行子分類。 –

回答

5

您不能覆蓋不會拋出異常的接口Runnable.run()。您必須改爲在run方法中處理異常。

try { 
    int i = in.read(); 
} catch (IOException e) { 
    // do something that makes sense for your application 
} 
1

您不能 - 在Threadrun()方法根本無法拋出unchecked異常。這實際上與匿名類沒有任何關係 - 如果您試圖直接擴展Thread,您會得到同樣的結果。

您需要計算出發生異常時想要發生的情況。你想要它殺死線程?以某種方式報告?考慮使用未經檢查的例外,頂級處理程序等。

0

您是否嘗試過使用try/catch?你可能會得到這個例外,只是因爲沒有一個恆定的流進來。

0

你需要處理異常或重新拋出一個未經檢查的異常。

InputStream in = ClientSocket.getInputStream(); 
new Thread() { 
    public void run() { 
    try { 
     while (true) { 
     int i = in.read(); 
     handleInput(i); 
     } 
    } catch (IOException iox) { 
     // handle, log or wrap in runtime exception 
    } 
    } 
}.start(); 
1

您不能「傳遞」異常,因爲此代碼運行在不同的線程中。它會被抓到哪裏?異常不是異步事件,它們是流控制結構。你可以在run方法中嘗試/捕獲它。

1

使用java.util.concurrent.Callable<V>代替:

final Callable<Integer> callable = new Callable<Integer>() { 

     @Override 
     public Integer call() throws Exception { 
      ... code that can throw a checked exception ... 
     } 
    }; 
    final ExecutorService executor = Executors.newSingleThreadExecutor(); 
    final Future<Integer> future = executor.submit(callable); 
    try { 
     future.get(); 
    } finally { 
     executor.shutdown(); 
    } 

你可以當你要處理Callable的結果對未來調用get()。它會拋出Callable投擲的任何異常。