有人可以告訴我如何修正這個錯誤在我的測試類 的第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()的簽名,就必須捕獲異常。 –