如何修复Catch语句中的SQLException?

时间:2011-08-30 03:05:00

标签: java swing postgresql intellij-idea

这个程序是关于自动完成的。当我向textfield输入内容时,会显示一系列建议。

当我向onWordUpdated()输入内容时,我会使用方法textfield获取数据库中的建议列表。

现在,问题是我有这个错误:

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();
  }

2 个答案:

答案 0 :(得分:7)

编译器只是告诉您此时不需要捕获该异常。

SQLException是一个经过检查的异常,这意味着如果您明确地抛出它,或者您调用一个在throws子句中声明它的方法,您的代码应该只能看到它。对于特定try / catch块中的代码,这些都不适用。

你应该能够摆脱内部的try / catch块,也可能是外层的。


IIRC,理论上可以看到尚未声明的已检查异常,但除非您采取特殊措施才能实现,否则不太可能出现这种情况。

答案 1 :(得分:6)

Java有两种类型的exceptions:未经检查(从RuntimeExceptionError继承)并检查(所有其他从Exception继承的)。

已检查的异常具有以下属性:

  • 如果一个代码块抛出一个,它必须在catch块中捕获,或者该方法必须声明它可能抛出该类型的Exception
  • 如果某些代码调用的方法throws SomeException,则该代码也必须位于try-catch中,或者其方法也必须指定throws SomeException

由于前两次检查,编译器可以检测是否实际可以在某个代码块中抛出已检查的异常。结果,这导致了第三个属性:

  • 如果try-catch块的catch子句声明Exception块中不能出现的try类型,则会生成编译错误。编译器主要是为了告诉你你犯了一个错误:你正在处理一个永远不会被抛出的异常。

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();
}