When using the Microsoft SQL Server 2005 JDBC Driver, all database error conditions are returned to your Java application as exceptions using the SQLServerException class. The following methods of the SQLServerException class are inherited from java.sql.SQLException and java.lang.Throwable; and they can be used to return specific information about the SQL Server error that has occurred:

In the following example, an open connection to the SQL Server AdventureWorks sample database is passed in to the function and a malformed SQL statement is constructed that does not have a FROM clause. Then, the statement is run and an SQL exception is processed.

public static void executeSQLException(Connection con) {
   try {
      String SQL = "SELECT TOP 10 * Person.Contact";
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(SQL);

      while (rs.next()) {
         System.out.println(rs.getString(4) + " " + rs.getString(6));
      }
      stmt.close();
   }
   catch (SQLException se) {
      do {
         System.out.println("SQL STATE: " + se.getSQLState());
         System.out.println("ERROR CODE: " + se.getErrorCode());
         System.out.println("MESSAGE: " + se.getMessage());
         System.out.println();
         se = se.getNextException();
      } while (se != null);
   }
}

See Also