【问题标题】:Catching the wrong exception捕获错误的异常
【发布时间】:2014-03-21 05:06:54
【问题描述】:

我试图在Java 中使用MySQL 捕获特定异常。但是,它运行的是 catch (SQLException ex) 而不是我想要的。

catch (MySQLIntegrityConstraintViolationException ex) {
}
catch (SQLException ex) {
}

得到以下错误,我希望它运行catch (MySQLIntegrityConstraintViolationException ex) 函数。

11:12:06 AM DAO.UserDAO createUser
SEVERE: null
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'idjaisjddiaij123ij' for key 'udid'

为什么它运行catch (SQLException ex) 而不是catch (MySQLIntegrityConstraintViolationException ex)

【问题讨论】:

  • 你能添加 ex.printStackTrace();在每个 catcha 中并粘贴异常?
  • 它是否会出现在.getCause() 中?

标签: java mysql exception exception-handling error-handling


【解决方案1】:

确保使用正确的命名空间。对我来说,附在图片上的那个就像一个魅力。

【讨论】:

    【解决方案2】:

    是的MySQL 总是在执行方法中抛出并捕获SQLException。你需要做的是在你的执行方法中捕获SQLException,它们会抛出新的MySQLIntegrityConstraintViolationException

    public void executeQuery() {
        try {
            // code
            rs = pstmt.executeQuery();
    } catch (SQLException ex) {
       throw new MySQLIntegrityConstraintViolationException(ex);
    }
    

    所以在调用execute方法的外部方法中,它应该只捕获MySQLIntegrityConstraintViolationException

    catch (MySQLIntegrityConstraintViolationException ex) {
       //handle ex
    }
    

    【讨论】:

    • 即使我也遇到过这种情况,萨拉赫所说的我也是。不知何故,在执行过程中你总是会得到 SQLException ,如果你知道你在寻找什么异常,那么从 SQLException 的 catch 块中抛出它是正确的方法。
    【解决方案3】:

    我建议使用ex instanceof MySQLIntegrityConstraintViolationException 来确保没有其他异常作为 MySQLIntegrityConstraintViolationException 引发,因为 SQLException 可能因多种不同原因引发。

    【讨论】:

      【解决方案4】:

      请导入

      com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
      

      我测试过,它会工作的。

      【讨论】:

      • 如果不导入此类,代码将如何编译?
      【解决方案5】:

      我遇到了同样的问题,我必须通过 JOptionPane 消息向用户显示错误类型。这是我的解决方案

      public boolean executeQuery() {
      try {
              // code
              rs = pstmt.executeQuery();
      } catch (SQLException ex) {
         int errCode = ex.getErrorCode();
           if(errCode == 1062){ //MySQLIntegrityConstraintViolationException 
           JOptionPane.showMessageDialog(null, "Duplicate entry for id.\n");}
           return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-11
        • 2010-12-14
        • 2014-08-26
        • 2017-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多