【问题标题】:JAVA SQL catching / declaring exceptionsJAVA SQL 捕获/声明异常
【发布时间】: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 块中获得了连接。 (rsst 可能为 null,因此请在调用 close 方法之前检查是否为 null。)
  • 如果在 catch 块中再次抛出异常,为什么会在 getData() 中捕获异常?抓住它不扔或不抓住并在 main 中的 getData 和 Catch 中添加 thorws。
  • getdata() 的签名表明它可以抛出异常。因此,在您调用它的地方,您需要捕获该异常,或者该调用方法的签名必须允许将异常进一步抛出调用堆栈。由于您是从 main 调用它,因此只要您保持 getData() 的签名保持现在的状态,就必须捕获异常。

标签: java mysql database jdbc


【解决方案1】:

您的 SQL 类中的方法引发异常,而在 main 方法中您不处理该异常。这是一个检查异常,所以你必须做一些事情。 至少你需要有一个这样的简单捕获

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();
    }
}

【讨论】:

    【解决方案2】:

    由于您的调用方法正在抛出异常,因此需要在被调用方法中捕获该异常。所以只需将您的调用放在 try catch 块中。

    【讨论】:

      【解决方案3】:

      这个问号有必要吗?不是错字,你的意思是别的吗? 这是java中的一些sqlconnections示例,它们看起来与您的有所不同。 How to make SQL connection statements common

      【讨论】:

        【解决方案4】:

        只需用try-catch 循环围绕您的线路

        【讨论】:

          【解决方案5】:
          public String getData() throws Exception {
              //
          }
          

          这里throws Exception表示这个方法可能会抛出Exception类型的异常,即checked exception

          所以必须在调用这个方法的时候处理。表示使用try/catch

          This article 可能会帮助您了解已检查和未检查的异常。

          【讨论】:

            猜你喜欢
            • 2016-11-16
            • 1970-01-01
            • 2016-03-10
            • 2010-11-25
            • 2012-10-26
            • 1970-01-01
            • 1970-01-01
            • 2017-09-18
            • 2016-07-05
            相关资源
            最近更新 更多