Java SQLException根据错误代码分开

我需要根据ErrorCode分离SQLExceptions.我在catch块中有以下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时输入意外的用户名时,会抛出以下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.

但我的抓住总是打印其他问题.如何根据上一个ErrorCode分隔不同的SQLExceptions?

最佳答案 – – 解决了 – –

首先感谢@blm的路由评论.

诡计是;其他即将发生的异常(第1和第2个)在其ErrorCode中的SQLState唯一数值中具有String值.

SQLException链第三个异常有28502 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
点赞