2015-04-30 22 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可能会帮助您了解已检查和未检查的例外情况。