2011-05-12 72 views
1

我有一個線程類和運行方法,我撥打電話到Web服務,該電話是在嘗試捕捉將調用方法拋出錯誤!

try { 
    // Make webs service call 
} 
catch (Exception e) { 
    throw e; 
} 

Eclipse不喜歡這個!

基本上我想拋出這個錯誤的調用方法,並在那裏處理?

+0

你是什麼意思「Eclipse不喜歡這個!」? – abalogh 2011-05-12 10:41:34

+0

未處理的異常類型異常 – 2011-05-12 10:46:52

+0

「拋出此錯誤的調​​用方法」,我懷疑這是可能的,調用方法生活在另一個線程... – Ishtar 2011-05-12 10:51:31

回答

4

如果你拋出checked異常,異常必須要麼用try/catch語句或聲明爲方法簽名拋出來處理。見exceptions tutorial;特別是關於The Three Kinds of Exceptions的部分。

+0

這裏還有一些關於方法重寫的內容。作爲[我在我的答案中添加](http://stackoverflow.com/questions/5976764/throw-error-to-calling-method/5976800#5976800) – 2011-05-12 10:59:55

3

那是因爲你重寫了run()而且重載將不允許你聲明更廣泛的異常被拋出。你可以把它包裝在RuntimeException

做它像

new Thread(new Runnable() { 

      public void run() { 
       try{ 
        //your code 
       }catch(Exception ex){ 
        throw new RuntimeException(ex);//or appropriate RuntimeException 
       } 
      } 
     }).start(); 

    } 
+0

[Runnable.run](http://download.oracle。 com/javase/1.4.2/docs/api/java/lang/Runnable.html#run%28%29)沒有聲明它拋出任何異常,所以你不能從它中拋出一個檢查異常。 – sudocode 2011-05-12 10:46:15

3

Yep java.lang.Exception被選中,所以你不能拋出它(因爲Runnable.run沒有在它的throws子句中聲明任何異常;它沒有throws子句)。你只能拋出RunTimeExceptions。你將不得不處理Checked Exceptions - 這是Java強迫你做的事情。一種方法是將檢查異常轉換爲RunTimeException,以便將其拋出。但不要忘記這是一個單獨的線程,所以請注意您的處理邏輯。

public class ThreadFun implements Runnable { 

    public void run() { 

     // LEGAL 
     try { 

     } catch (RuntimeException e) { 
      throw e; 
     } 

     // NOT LEGAL 
     try { 

     } catch (Exception e) { 
      throw e; 
     }   
    } 
} 
0

而不是捕捉異常,將throws Exception添加到方法簽名。這將強制調用方法來捕獲異常。

+0

正如在線程中所說,這不會像Runnable.run沒有拋出子句。 – planetjones 2011-05-12 10:56:15

相關問題