2015-04-30 23 views
-1

有人可以告訴我如何修正這個錯誤在我的測試類 的第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; 
     } 
    } 
} 
+0

好像你也應該有一個'finally'塊(在catch塊之後),它關閉結果集並關閉語句。並關閉連接,因爲你已經在try塊中獲得了連接。 (可能'rs'和'st'可能爲空,因此在調用close方法之前檢查null。) – spencer7593

+0

爲什麼你在捕獲getData()中的異常(如果你在catch塊中再次拋出異常)?抓住它,不要拋出或不捕獲,並添加thorws getData和Catch主。 – Garry

+0

getdata()的簽名表明它可以拋出異常。因此,在您調用它的地方,您需要捕獲該異常,或者該調用方法的簽名必須允許將該異常拋入調用堆棧。既然你是從main調用的,只要你按照現在的方式保存getData()的簽名,就必須捕獲異常。 –

回答

0

當您的調用方法是把它扔需要趕上稱爲method.So只是把那個異常異常你的電話嘗試catch塊。

1

SQL類中的方法拋出異常,並且在主方法中不處理該異常。這是一個檢查的異常,所以你必須做一些事情。 至少你需要有這樣一個簡單的接球

public static void main(String[] args) { 

    SQL sql = new SQL(); 
    try{ 
     sql.getData();//Error here "Unreported exception Exception; must be caught or declared to be thrown" 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 
0

簡單地環繞你行以try-catch

0
public String getData() throws Exception { 
    // 
} 

這裏throws Exception意味着這種方法可能會拋出Exception類型的異常,這是一個checked exception

因此,它必須在調用此方法時處理。意味着使用try/catch

This article可能會幫助您瞭解已檢查和未檢查的例外情況。