有人可以告诉我如何修正这个错误在我的测试类 的第8行,我不知道跆拳道是错了,或如何,甚至寻找解决方案JAVA SQL捉/宣称例外
主类
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'可能为空,因此在调用close方法之前检查null。) – spencer7593
为什么你在捕获getData()中的异常(如果你在catch块中再次抛出异常)?抓住它,不要抛出或不捕获,并添加thorws getData和Catch主。 – Garry
getdata()的签名表明它可以抛出异常。因此,在您调用它的地方,您需要捕获该异常,或者该调用方法的签名必须允许将该异常抛入调用堆栈。既然你是从main调用的,只要你按照现在的方式保存getData()的签名,就必须捕获异常。 –