未报告的异常java.sql.SQLException;必须被抓或宣布被扔?

时间:2010-12-16 04:09:20

标签: java

我在尝试编译以下代码时遇到此错误。我想知道我做错了什么。

unreported exception java.sql.SQLException; must be caught or declared to be thrown
 Class.forName(myDriver);

               ^
private void setupInfo() {

    Driver driver = new org.gjt.mm.mysql.Driver();
    String url = "jdbc:mysql://localhost:3306/test";
    String username = "root";
    String password = "123456";

    String problemFeatureSpecTableName = "ProblemFeatureSpec";
    String solutionFeatureSpectTableName = "SolutionFeatureSpec";
    String classTableName = "Class";
    String extraDataTableName = "ExtraData";
    String casebaseTablename = "CaseBase";
    String problemTableName = "Problem";
    String solutionTableName = "Solution";
    String inactiveContextsTableName = "InactiveContext";
    String constantsTableName = "Constants";
    dbInfo = new DBInfo(new JDBCDriverInfo(driverName, url, username, password),constantsTableName);
    problemSpecInfo = new FeatureSpecRDBInfo(problemFeatureSpecTableName, classTableName, extraDataTableName);
    solutionSpecInfo = new FeatureSpecRDBInfo(solutionFeatureSpectTableName, classTableName, extraDataTableName);
    rdbCasebaseInfo = new RDBCaseBaseInfo(casebaseTablename, solutionTableName, problemTableName, inactiveContextsTableName);
}

4 个答案:

答案 0 :(得分:13)

您需要在方法中捕获异常:

public void setupInfo()
{
    try
    {
        // call methods that might throw SQLException
    }
    catch (SQLException e)
    {
        // do something appropriate with the exception, *at least*:
        e.printStackTrace();
    }
}

声明投掷SQLException的方法:

private void setupInfo() throws SQLException
{
    // call methods that might throw SQLException
}

答案 1 :(得分:2)

抓住异常或扔掉它。更好地使用IDE(Eclipse或Netbeans),它会在您按Enter键时告诉您错误。

答案 2 :(得分:1)

这行代码抛出了一个未被捕获的异常:

Driver driver = new org.gjt.mm.mysql.Driver();

试试这个:

try {
   Driver driver = new org.gjt.mm.mysql.Driver();
}
catch (java.sql.SQLException e) {
  // you may want to do something useful here
 // maybe even throw new RuntimException();
}

答案 3 :(得分:1)

始终尝试从IDE获取帮助。 IDE通常可以自动修复错误。按下alt +在Eclipse中输入IntelliJ IDEA或ctrl + 1并选择修复错误。