有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试根据错误代码捕获Java SQLException separate

我需要根据ErrorCode分隔SQLExceptions。我在catch block中有以下if语句,但是else条件总是打印出来的

catch (SQLException ex) {

      if (ex.getErrorCode() == 28502){
         System.out.println("Username Problem");
      }

      else{
         System.out.println("Other Problem");
      }  

     Logger.getLogger(FirstTimeMainFrame.class.getName()).log(Level.SEVERE, null, ex);

}

实际上,当我在创建DB时输入意外的username时,会抛出以下SQLExceptions

java.sql.SQLException: Failed to create database 'myDB', see the next exception for details.
//rest of exception.
Caused by: ERROR XJ041: Failed to create database 'myDB', see the next exception for details.
//rest of exception.
Caused by: ERROR XBM01: Startup failed due to an exception. See next exception for details
//rest of exception.
Caused by: ERROR 28502: The user name 'AAA.AAA' is not valid.
//rest of exception.

但是我的catch总是打印Other Problem。如何根据上一个ErrorCode分隔不同的SQLExceptions


共 (2) 个答案

  1. # 1 楼答案

    -已解决-

    感谢您对@blm first的评论

    技巧是其他即将到来的Exceptions(第一和第二)在其SQLState中有String值,在其ErrorCode中只有数值

    SQLException第三链exception既有SQLState又有ErrorCode。我想这就是第一和第二的区别

    所以我改变了主意

    捕捉块

    catch (SQLException se) {
    
          do {
    
             if(se.getSQLState().equals("28502")){
                System.out.println("Username Problem");
             }
    
             else{
                System.out.println("Other Problem");
             }  
    
          } while ((se = se.getNextException()) != null);
    
    }
    

    输出为

    Other Problem
    Other Problem
    Username Problem
    
  2. # 2 楼答案

    您应该使用捕获的SqlExeption对象的“getCause()”方法获取原因异常。然后,您可以将结果强制转换为异常并检查其错误代码
    检查此项以了解更多信息:Throwable.getCause()

    编辑:

    SQLException temp = ex;
    while(temp.getCause() != null)
    {
         temp = (Exception)temp.getCause();
    }
    //  check if temp is SQLException and if it is check ((SQLException)temp).getErrorCode() == whatever you want