2011-08-30 1166 views
0

這個程序是關於自動完成的。當我輸入textfield時,會出現一個建議列表。如何解決Catch語句中的SQLException?

當我在textfield上輸入內容時,我會對DB的建議列表做出方法onWordUpdated()。現在

,問題是我有這樣的錯誤:

exception java.sql.SQLException is never thrown in body of corresponding try statement 

我在代碼中所做的評論,這樣你就會知道哪些線。

有人可以幫我解決這個問題嗎?

感謝..

我有這樣的代碼:

public void onWordUpdated(final String toComplete) 
    { 
    new Thread(new Runnable() 
    { 
     public void run() 
     { 
     try 
     { 
      final List<Suggestion> suggestions = suggestor.getSuggestions(toComplete); 
      SwingUtilities.invokeLater(new Runnable() 
      { 
      public void run() 
      { 
       try 
       { 
       suggestionWidgetModel.clear(); 
       for (Suggestion suggestion : suggestions) 
        suggestionWidgetModel.addElement(suggestion.getCaption()); 
       if (!suggestions.isEmpty()) 
        suggestionWidget.setSelectedIndex(0); 
       } 
       catch (SQLException e) // This line is my problem, Could someone help me how to fix this? Thanks.. 
       { 
       e.printStackTrace(); 
       } 
      } 
      }); 
     } 
     catch (SQLException e1) 
     { 
      onSqlError(e1); 
     } 
     } 
    }, "onWordUpdated").start(); 
    } 
+5

請使用代碼僅用於說明目的。很難理解代碼與問題無關的問題以及隱藏在評論中的問題。 – topchef

+5

SQLException說什麼? –

+1

究竟是什麼問題?你期望你的代碼做什麼,它究竟在做什麼?如果它拋出一個你不期望的異常,你能提供更多關於它的意思的信息嗎? –

回答

7

編譯器只是簡單地告訴你,你不需要在那個時候捕獲該異常。

SQLException是一個檢查異常,這意味着如果你明確地拋出它,或者你調用一個聲明它在throws子句中的方法,你的代碼應該只能看到它。這些特定的try/catch塊中的代碼都不是這樣。

你應該能夠擺脫內部try/catch塊,也可能是外部塊。


IIRC,這在理論上是可能看到尚未宣佈檢查異常,但出現這種可能性不大,除非你採取特殊的措施來做到這一點。

+0

當我嘗試刪除try/catch塊時,出現錯誤:線程「main」中的異常java.lang.ClassNotFoundException:org.postgresql.Driver – sack

+4

這是一個不同的問題。您的類路徑中沒有Postgres驅動程序。 –

+0

@Stephen - 「理論上可以看到沒有被聲明的檢查過的異常」 - 我對此很好奇。你能否解釋或鏈接到一個討論詳細說明? –

6

Java有兩種類型的exceptions:選中(那些從RuntimeExceptionError繼承),並檢查(從Exception繼承所有其他) 。

檢查異常具有以下屬性:

  • 如果一個代碼塊拋出一個,它必須在catch塊被捕獲或者該方法必須聲明它可能拋出該類型的Exception
  • 如果某些代碼調用方法throws SomeException,那麼該代碼也必須處於try-catch或其方法中,還必須指定throws SomeException

由於前兩次檢查,編譯器可以檢測到檢查的異常是否可以實際拋出某個代碼塊。其結果是,這導致了第三個屬性:

  • 如果try-catch塊的catch子句聲明不能在try塊發生Exception型,則生成編譯錯誤。編譯器這樣做主要是爲了告訴你,你犯了一個錯誤:你正在處理一個永遠不會拋出的異常。

SQLException是一個檢查異常,所以它受制於這些規則。下面的try塊中的代碼行(或它們調用的方法)都不會拋出SQLException,所以編譯器會通過編譯錯誤告訴您。

try { 
    suggestionWidgetModel.clear(); 
    for (Suggestion suggestion : suggestions) 
     suggestionWidgetModel.addElement(suggestion.getCaption()); 
    if (!suggestions.isEmpty()) 
     suggestionWidget.setSelectedIndex(0); 
} 
catch (SQLException e) // This line is my problem, Could someone help me how to fix this? Thanks.. 
{ 
    e.printStackTrace(); 
} 
+0

當我嘗試刪除try/catch塊時,出現如下錯誤:線程「main」中出現異常java.lang.ClassNotFoundException:org.postgresql.Driver – sack