Search code examples
javatry-catchderbysqlexception

Java SQLException separate according to errorcode


I need to separate SQLExceptions according to ErrorCode. I have the following if statement in catch block but the else condition is printed always.

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

}

Actually, when I enter unexpected username when creating DB, the following SQLExceptions are thrown.

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.

But my catch is always print Other Problem. How can I separate different SQLExceptions according to last ErrorCode?


Solution

  • --- SOLVED ---

    Thanks for the routed comments for @blm first.

    Trick is; Other coming Exceptions (1st and 2nd) has String values in their SQLState only numeric value in their ErrorCode.

    SQLException chain 3rd exception has 28502 both SQLState and ErrorCode. This is the difference between 1st and 2nd Exceptions i think.

    So i have changed my

    Catch Block;

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

    Output is;

    Other Problem
    Other Problem
    Username Problem