【发布时间】:2015-04-30 13:45:27
【问题描述】:
谁能告诉我如何修复我的测试类第 8 行的错误 我不知道 wtf 有什么问题,也不知道如何寻找解决方案
主类
package T;
public class Test {
public static void main(String[] args) {
SQL sql = new SQL();
sql.getData();//Error here "Unreported exception Exception; must be caught or declared to be thrown"
}
}
SQL 类
package T;
public class SQL {
private Connection connect = null;
public String getData() throws Exception {
String name = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/vehicles?" + "user=sqluser&password=sqluserpw");
Statement st = connect.createStatement();
ResultSet rs = st.executeQuery("SELECT * from vehicles.test");
if (rs.next()) {
name = rs.getString("word");
}
return name;
}
catch (Exception e) {
throw e;
}
}
}
【问题讨论】:
-
似乎您还应该有一个
finally块(在 catch 块之后)关闭结果集并关闭语句。并关闭连接,因为您已经在 try 块中获得了连接。 (rs和st可能为 null,因此请在调用 close 方法之前检查是否为 null。) -
如果在 catch 块中再次抛出异常,为什么会在 getData() 中捕获异常?抓住它不扔或不抓住并在 main 中的 getData 和 Catch 中添加 thorws。
-
getdata() 的签名表明它可以抛出异常。因此,在您调用它的地方,您需要捕获该异常,或者该调用方法的签名必须允许将异常进一步抛出调用堆栈。由于您是从 main 调用它,因此只要您保持 getData() 的签名保持现在的状态,就必须捕获异常。