SQLException, SQL state and error codes
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A duplicate email, a missing table and a server that is down need very different handling, yet JDBC reports all three as the same exception type. Three small details tell them apart.
getMessage, getSQLState and getErrorCode
SQLException is the checked exception that JDBC methods throw when the driver or the database reports a problem. It carries a message, a SQL state and an error code.
Catch the SQLException and ask it three questions. Example 1 triggers a duplicate email and prints the message, the SQL state and the error code.
Example 1 · One real failure, three details
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;
public class DuplicateEmailDemo { public static void main(String[] args) { String sql = "INSERT INTO customers (full_name, email, phone) VALUES (?, ?, ?)"; try (Connection conn = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, "Asha R"); ps.setString(2, "asha.rao@example.com"); // already used by customer 1 ps.setString(3, "9000011111"); ps.executeUpdate(); System.out.println("Saved"); } catch (SQLException e) { System.out.println("Class : " + e.getClass().getName()); System.out.println("Message : " + e.getMessage()); System.out.println("SQL state : " + e.getSQLState()); System.out.println("Error code: " + e.getErrorCode()); } }}Class : java.sql.SQLIntegrityConstraintViolationException Message : Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' SQL state : 23000 Error code: 1062
What this code does
- Customer 1 already uses
asha.rao@example.com, so the UNIQUE constraintuq_customers_emailrejects the insert. - The message names the value and the key, which is great for a log. The state
23000says "constraint broken" in a way every database understands, and1062says exactly "duplicate key" in MySQL terms. - Connector/J also picked the subclass
SQLIntegrityConstraintViolationException, because the state starts with 23.
The three details:
getMessage(): the text MySQL sends, written for people and for logs.getSQLState(): a five-character code from the SQL standard, such as23000. Other databases use the same states for the same kinds of problem.getErrorCode(): the database's own number, such as MySQL's1062.
MySQL error codes you will meet
An error code is the database's own number for one exact problem, such as MySQL's 1062 for a duplicate key. It is more precise than the SQL state, but it means something only for MySQL.
A handful of MySQL error codes cover most of what a shop app meets. Example 2 triggers five of them from the ShopLite tables and constraints.
Example 2 · Five common errors from the ShopLite database
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;
public class CommonErrorsDemo { static final String URL = System.getenv("DB_URL"); static final String USER = System.getenv("DB_USER"); static final String PASSWORD = System.getenv("DB_PASSWORD");
static void run(String label, String sql) { try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); Statement st = conn.createStatement()) { st.execute(sql); System.out.println(label + ": worked"); } catch (SQLException e) { print(label, e); } }
static void print(String label, SQLException e) { System.out.println(label); System.out.println(" " + e.getErrorCode() + " | " + e.getSQLState() + " | " + e.getMessage()); }
public static void main(String[] args) { run("Duplicate email", "INSERT INTO customers (full_name, email) VALUES ('Asha R', 'asha.rao@example.com')"); run("Order item for a product that does not exist", "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (1, 999, 1, 100.00)"); run("Delete a product that has orders", "DELETE FROM products WHERE product_id = 1"); run("Table name typo", "SELECT * FROM product");
try (Connection conn = DriverManager.getConnection(URL, USER, "wrong-password")) { System.out.println("Login: worked"); } catch (SQLException e) { print("Wrong password", e); } }}Duplicate email 1062 | 23000 | Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' Order item for a product that does not exist 1452 | 23000 | Cannot add or update a child row: a foreign key constraint fails (`shoplite`.`order_items`, CONSTRAINT `fk_order_items_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`)) Delete a product that has orders 1451 | 23000 | Cannot delete or update a parent row: a foreign key constraint fails (`shoplite`.`order_items`, CONSTRAINT `fk_order_items_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`)) Table name typo 1146 | 42S02 | Table 'shoplite.product' doesn't exist Wrong password 1045 | 28000 | Access denied for user 'shoplite_app'@'localhost' (using password: YES)
What this code does
- 1452 and 1451 both come from the foreign key
fk_order_items_product: one when a child points to a missing product, the other when a product that is still ordered would be deleted. Both have state23000, so only the code tells them apart. - 1146 has state
42S02(class 42: fix the code) and 1045 has state28000(failed login). The user in the message is the one fromDB_USER. - Every statement failed, so the data in ShopLite is unchanged and the program can run again.
These codes cover most cases:
- 1062
Duplicate entry ... for key ...: a UNIQUE or PRIMARY KEY value already exists, such as an email or a SKU. - 1452
Cannot add or update a child row: the new row points to a parent that does not exist. 1451Cannot delete or update a parent row: other rows still point to this one. - 1045
Access denied for user: wrong user name or password, with SQL state28000. - 1146
Table ... doesn't exist: a typo in the table name, or the wrong database in the URL.
SQL state classes: 23, 08 and 42
A SQL state class is the first two characters of the SQL state. Class 23 means a broken constraint, 08 a connection problem and 42 a syntax error or a missing table, column or permission.
The first two characters of a SQL state are its class, a group of related problems. The class is often all you need to decide what to do. Example 3 sorts errors by class.
Example 3 · Classifying by SQL state class
import java.sql.SQLException;import java.util.List;
public class SqlStateClassDemo { static String kindOf(SQLException e) { String state = e.getSQLState(); if (state == null || state.length() < 2) { return "unknown"; } switch (state.substring(0, 2)) { case "23": return "constraint broken: fix the data"; case "08": return "connection problem: check the server"; case "42": return "bad SQL or no permission: fix the code"; case "28": return "login failed: check user and password"; default: return "other (" + state + ")"; } }
public static void main(String[] args) { // The same messages, states and codes MySQL sent back in the earlier examples List<SQLException> errors = List.of( new SQLException("Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'", "23000", 1062), new SQLException("Cannot delete or update a parent row: a foreign key constraint fails", "23000", 1451), new SQLException("Communications link failure", "08S01", 0), new SQLException("Too many connections", "08004", 1040), new SQLException("You have an error in your SQL syntax", "42000", 1064), new SQLException("Table 'shoplite.product' doesn't exist", "42S02", 1146), new SQLException("Access denied for user 'shoplite_app'@'localhost' (using password: YES)", "28000", 1045), new SQLException("Check constraint 'chk_products_stock' is violated.", "HY000", 3819));
for (SQLException e : errors) { System.out.printf("%-5s %-5d -> %s%n", e.getSQLState(), e.getErrorCode(), kindOf(e)); } }}23000 1062 -> constraint broken: fix the data 23000 1451 -> constraint broken: fix the data 08S01 0 -> connection problem: check the server 08004 1040 -> connection problem: check the server 42000 1064 -> bad SQL or no permission: fix the code 42S02 1146 -> bad SQL or no permission: fix the code 28000 1045 -> login failed: check user and password HY000 3819 -> other (HY000)
What this code does
- The exceptions are built with the same messages, states and codes MySQL sent in the earlier examples, so this program runs without a database.
new SQLException(message, state, code)is a real JDBC constructor. kindOflooks only at the first two characters. Duplicate keys and foreign keys land in one group;Communications link failureandToo many connectionsland in another.- The CHECK constraint failure (3819,
HY000) falls through toother, a reminder that the class does not catch every data problem.
What each class asks you to do:
23: an integrity constraint was broken (duplicate key, foreign key, NOT NULL). The user's data must change.08: a connection problem (server down, network lost, too many connections). Retrying later may work.42: a syntax error or a missing table, column or permission. The code or the setup must change.28is a failed login. MySQL also sendsHY000, a general class, for many of its own errors.
Predict the output
Which class is it?
Read the code and pick what it prints.
Round 1 of 3
The INSERT repeats an email that is already in customers.
stock >= 0, arrives as error 3819 with state HY000. getSQLState() can also be null for some driver-made exceptions, so check before calling substring.Subclasses of SQLException
SQLTransientException is a subclass of SQLException for an error that may succeed if the same statement is tried again later, such as a deadlock or a pool with no free connection.
JDBC has subclasses of SQLException for common groups, so you can catch a kind of error instead of comparing codes. Example 4 catches by subclass.
Example 4 · Catching by subclass
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.SQLIntegrityConstraintViolationException;import java.sql.SQLRecoverableException;import java.sql.SQLSyntaxErrorException;import java.sql.Statement;
public class SubclassCatchDemo { static final String USER = System.getenv("DB_USER"); static final String PASSWORD = System.getenv("DB_PASSWORD");
static void attempt(String label, String url, String sql) { System.out.println(label); try (Connection conn = DriverManager.getConnection(url, USER, PASSWORD); Statement st = conn.createStatement()) { st.execute(sql); System.out.println(" worked"); } catch (SQLIntegrityConstraintViolationException e) { System.out.println(" constraint catch <- " + e.getClass().getSimpleName()); } catch (SQLSyntaxErrorException e) { System.out.println(" syntax catch <- " + e.getClass().getSimpleName()); } catch (SQLRecoverableException e) { System.out.println(" recoverable catch <- " + e.getClass().getSimpleName()); } catch (SQLException e) { System.out.println(" general catch <- " + e.getClass().getSimpleName()); } }
public static void main(String[] args) { String url = System.getenv("DB_URL"); attempt("1. Duplicate email", url, "INSERT INTO customers (full_name, email) VALUES ('Asha R', 'asha.rao@example.com')"); attempt("2. Misspelt column", url, "SELECT prise FROM products"); attempt("3. Stock below zero", url, "UPDATE products SET stock = -1 WHERE product_id = 1"); attempt("4. Nothing listening on port 3399", "jdbc:mysql://localhost:3399/shoplite", "SELECT 1"); }}1. Duplicate email constraint catch <- SQLIntegrityConstraintViolationException 2. Misspelt column syntax catch <- SQLSyntaxErrorException 3. Stock below zero general catch <- SQLException 4. Nothing listening on port 3399 recoverable catch <- CommunicationsException
What this code does
- Each failure lands in a different
catch: the duplicate in the constraint block, the misspelt column (1054) in the syntax block, the refused connection in the recoverable block. - The negative stock breaks the CHECK constraint, yet it reaches the general
SQLExceptionblock, because MySQL reports it with stateHY000. - The specific blocks come first. If
catch (SQLException e)were the first block, the compiler would reject the later ones as already caught.
Connector/J chooses the subclass mostly from the SQL state. Catch the specific ones first and plain SQLException last, because a catch for a parent class also catches every child.
The subclasses to know:
SQLIntegrityConstraintViolationException(state 23) andSQLSyntaxErrorException(state 42): both areSQLNonTransientException, so repeating the same statement fails again.SQLTransientException: its children includeSQLTransientConnectionException, which HikariCP throws when no pooled connection is free in time (Connection Pooling module), andSQLTransactionRollbackExceptionfor deadlocks.SQLRecoverableException: works again after reconnecting. Connector/J'sCommunicationsException(server down or network lost) is one.SQLNonTransientConnectionException: for exampleToo many connections(1040) or using a closed connection.
Fix the error
Fix the catch order
Read the error, then pick the line that fixes it.
Pick the line that replaces line 5 so the code compiles.
Error
error: exception SQLIntegrityConstraintViolationException has already been caught
Chained exceptions and the cause
The root cause is the exception at the bottom of a chain of causes, found by following getCause() until it returns null. It usually says most clearly what went wrong.
A connection failure is a chain of exceptions, each the cause of the one above it. Examples 5 and 6 follow getCause() down to the root.
Example 5 · Following the cause of a connection failure
Runs in: a Maven project with the MySQL driver (no server needed on port 3399)
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class CauseChainDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3399/shoplite"; // nothing listens on this port try (Connection conn = DriverManager.getConnection(url, System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { System.out.println("Connected"); } catch (SQLException e) { System.out.println("SQL state: " + e.getSQLState()); int level = 0; for (Throwable t = e; t != null; t = t.getCause()) { String firstLine = String.valueOf(t.getMessage()).lines().findFirst().orElse(""); System.out.println(" ".repeat(level) + t.getClass().getName()); System.out.println(" ".repeat(level) + " " + firstLine); level++; } } }}SQL state: 08S01
com.mysql.cj.jdbc.exceptions.CommunicationsException
Communications link failure
com.mysql.cj.exceptions.CJCommunicationsException
Communications link failure
java.net.ConnectException
Connection refused: connectWhat this code does
- The loop starts at the caught exception and follows
getCause()until it reachesnull, printing the class and the first line of each message. - State
08S01says "connection problem"; the root causejava.net.ConnectExceptionsays why: nothing is listening on that port. On macOS the last line readsConnection refusedwithout: connect. - In a real app you log the whole chain; a logger prints it as
Caused by:lines in the stack trace.
Example 6 · A failed batch and its chain
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.BatchUpdateException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement;import java.util.Arrays;
public class BatchErrorDemo { public static void main(String[] args) throws SQLException { String[][] rows = { {"Rohan Das", "rohan.das@example.com"}, {"Asha R", "asha.rao@example.com"}, // this email already exists {"Sneha Pillai", "sneha.pillai@example.com"}};
try (Connection conn = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { String sql = "INSERT INTO customers (full_name, email) VALUES (?, ?)"; try (PreparedStatement ps = conn.prepareStatement(sql)) { for (String[] row : rows) { ps.setString(1, row[0]); ps.setString(2, row[1]); ps.addBatch(); } ps.executeBatch(); } catch (BatchUpdateException e) { System.out.println("Update counts: " + Arrays.toString(e.getUpdateCounts())); System.out.println("Cause: " + e.getCause().getClass().getSimpleName()); System.out.println("Every exception in the chain:"); for (Throwable t : e) { // SQLException is Iterable<Throwable> System.out.println(" " + t.getClass().getSimpleName() + ": " + t.getMessage()); } }
// Clean up so the demo can run again try (Statement st = conn.createStatement()) { st.executeUpdate("DELETE FROM customers WHERE email IN" + " ('rohan.das@example.com', 'sneha.pillai@example.com')"); } } }}Update counts: [1, -3, 1] Cause: SQLIntegrityConstraintViolationException Every exception in the chain: BatchUpdateException: Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' SQLIntegrityConstraintViolationException: Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'
What this code does
getUpdateCounts()has one number per row: 1 for each inserted row, and -3 (Statement.EXECUTE_FAILED) for the duplicate. With MySQL's default settings the driver carries on after a failed row.- The
BatchUpdateExceptionkeeps the real MySQL error as its cause, and the for-each loop over the exception prints both. - The last statement deletes the two new customers, so the demo leaves the data as it found it.
For a refused connection the chain is Connector/J's CommunicationsException, an internal exception, then java.net.ConnectException: Connection refused.
JDBC has a second chain too, getNextException(), for several errors from one call. SQLException implements Iterable<Throwable>, so a for-each loop walks the exception, its causes and its next exceptions. Connector/J puts the details of a failed batch in the cause of the BatchUpdateException, as Example 6 shows.
Next step
Check your understanding
12 quick questions