Turning SQL errors into meaningful application exceptions
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)If every layer of the app must handle SQLException, the menu ends up knowing about SQL states it cannot act on. Callers need to hear "email taken" or "database unavailable", not a SQL state.
Why callers should not deal with SQLException
A checked exception is an exception that the compiler forces every method to catch or declare with throws. SQLException is one, so it spreads to every caller.
The compiler forces every method that can throw SQLException to catch it or declare it. Example 1 shows the declaration spreading from the SQL method to every caller.
Example 1 · Checked SQLException spreads to every caller
import java.sql.SQLException;import java.util.List;
class CustomerQueries { // Stands in for a real JDBC query; Jaipur plays the part of a failed connection int countByCity(String city) throws SQLException { if (city.equals("Jaipur")) { throw new SQLException("Communications link failure", "08S01"); } return city.equals("Chennai") ? 2 : 1; }}
class CityReport { private final CustomerQueries queries = new CustomerQueries();
// Has nothing to do with SQL, yet it must mention SQLException String line(String city) throws SQLException { return "Customers in " + city + ": " + queries.countByCity(city); }}
public class CheckedSpreadDemo { public static void main(String[] args) { CityReport report = new CityReport(); for (String city : List.of("Chennai", "Pune", "Jaipur")) { try { System.out.println(report.line(city)); } catch (SQLException e) { // the menu now depends on java.sql too System.out.println("Customers in " + city + ": failed, SQL state " + e.getSQLState()); } } }}Customers in Chennai: 2 Customers in Pune: 1 Customers in Jaipur: failed, SQL state 08S01
What this code does
CustomerQueriesstands in for JDBC code (Jaipur plays a failed connection), so the program runs without a database. The point is the method signatures.CityReport.linehas no SQL in it, yet it must declarethrows SQLException, andmainmust importjava.sqland catch it.- The best
maincan do with the exception is print the state08S01, which means nothing to a user.
The report code, the menu and every layer in between must mention SQLException too, though they have nothing to do with SQL. It also blocks lambdas: cities.stream().map(city -> countByCity(city)) does not compile, because javac reports unreported exception SQLException; must be caught or declared to be thrown and map takes a function that cannot throw checked exceptions.
And the menu cannot do anything useful with state 08S01 anyway: it needs to know "database unavailable" or "email taken".
An unchecked DataAccessException that keeps the cause
An unchecked exception is an exception that extends RuntimeException. The compiler does not force any method to catch or declare it, so lambdas can throw it freely.
A DataAccessException is your own class for "reading or writing data failed". It extends RuntimeException, so no method must declare it. Example 2 keeps the SQLException inside it as the cause.
Example 2 · DataAccessException with the SQLException as its cause
import java.sql.SQLException;import java.util.List;
class DataAccessException extends RuntimeException { DataAccessException(String message, Throwable cause) { super(message, cause); }}
class CustomerQueries { int countByCity(String city) { try { return runCountQuery(city); } catch (SQLException e) { throw new DataAccessException("Could not count customers in " + city, e); // keep e as the cause } }
// Stands in for the real JDBC code; Jaipur plays the part of a failed connection private int runCountQuery(String city) throws SQLException { if (city.equals("Jaipur")) { throw new SQLException("Communications link failure", "08S01"); } return city.equals("Chennai") ? 2 : 1; }}
public class DataAccessExceptionDemo { public static void main(String[] args) { CustomerQueries queries = new CustomerQueries();
List<Integer> counts = List.of("Chennai", "Pune").stream() .map(queries::countByCity) // compiles now: no checked exception .toList(); System.out.println("Counts: " + counts);
try { queries.countByCity("Jaipur"); } catch (DataAccessException e) { System.out.println("Message : " + e.getMessage()); System.out.println("Cause : " + e.getCause().getClass().getName()); SQLException cause = (SQLException) e.getCause(); System.out.println("SQL state: " + cause.getSQLState()); } }}Counts: [2, 1] Message : Could not count customers in Jaipur Cause : java.sql.SQLException SQL state: 08S01
What this code does
countByCityno longer declaresthrows SQLException, soqueries::countByCityworks insidestream().map(...).- The new message says what the app was doing;
getCause()still returns the originalSQLException, with state08S01, for the log. - The cast
(SQLException) e.getCause()is safe here because this class always wraps aSQLException.
The key is the constructor DataAccessException(String message, Throwable cause), which passes both to super. The message says what the application was doing ("Could not count customers in Jaipur"); the cause is the original SQLException with its state, code and stack trace. Spring uses the same idea, and its exception has the same name.
Specific exceptions: DuplicateEmailException, ProductNotFoundException
Exception translation means catching a low-level exception, such as SQLException, where it happens and throwing one in the application's language, such as DuplicateEmailException, with the original attached as the cause.
A specific exception is a subclass for one situation the caller handles differently: DuplicateEmailException means "ask for another email". Example 3 translates real query errors.
Example 3 · Specific exceptions from real queries
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
class DataAccessException extends RuntimeException { DataAccessException(String message, Throwable cause) { super(message, cause); }
DataAccessException(String message) { super(message); }}
class DuplicateEmailException extends DataAccessException { DuplicateEmailException(String email, SQLException cause) { super("Email already registered: " + email, cause); }}
class ProductNotFoundException extends DataAccessException { ProductNotFoundException(int productId) { super("No product with id " + productId); }}
record Product(int id, String name, BigDecimal price) {}
class ShopQueries { private static final int DUPLICATE_KEY = 1062; // MySQL error code private final String url = System.getenv("DB_URL"); private final String user = System.getenv("DB_USER"); private final String password = System.getenv("DB_PASSWORD");
int registerCustomer(String fullName, String email) { String sql = "INSERT INTO customers (full_name, email) VALUES (?, ?)"; try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, fullName); ps.setString(2, email); ps.executeUpdate(); try (ResultSet keys = ps.getGeneratedKeys()) { keys.next(); return keys.getInt(1); } } catch (SQLException e) { if (e.getErrorCode() == DUPLICATE_KEY) { throw new DuplicateEmailException(email, e); } throw new DataAccessException("Could not register customer " + email, e); } }
Product findProduct(int id) { String sql = "SELECT product_id, name, price FROM products WHERE product_id = ?"; try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement ps = conn.prepareStatement(sql)) { ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { throw new ProductNotFoundException(id); // no SQL error, but still a failure } return new Product(rs.getInt("product_id"), rs.getString("name"), rs.getBigDecimal("price")); } } catch (SQLException e) { throw new DataAccessException("Could not load product " + id, e); } }}
public class SpecificExceptionsDemo { public static void main(String[] args) { ShopQueries queries = new ShopQueries();
try { queries.registerCustomer("Asha R", "asha.rao@example.com"); } catch (DuplicateEmailException e) { System.out.println(e.getMessage()); System.out.println(" cause: " + e.getCause().getMessage()); }
System.out.println(queries.findProduct(3)); try { queries.findProduct(99); } catch (ProductNotFoundException e) { System.out.println(e.getMessage()); System.out.println(" is a DataAccessException: " + (e instanceof DataAccessException)); } }}Email already registered: asha.rao@example.com cause: Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' Product[id=3, name=iPhone 15 128GB, price=69900.00] No product with id 99 is a DataAccessException: true
What this code does
registerCustomerturns MySQL error 1062 intoDuplicateEmailException, keeping theSQLIntegrityConstraintViolationExceptionas the cause. Any other SQL failure becomes a generalDataAccessException.findProduct(99)causes no SQL error at all: the query finds no row, and the method throwsProductNotFoundExceptionitself.- Both are
DataAccessExceptions, so onecatch (DataAccessException e)could handle them together when the caller does not need the difference.
Because the specific exceptions extend DataAccessException, a caller that does not care can still catch the parent. The translation happens in the method that runs the SQL, the only place that knows both the error code and what it means: 1062 on the customers insert is a duplicate email.
"Not found" is not even a SQL error: a SELECT that finds no row just returns an empty result, so the query method throws ProductNotFoundException itself.
Catch, translate, rethrow: never swallow
Swallowing an exception means catching it and carrying on as if nothing happened: an empty catch, one that only prints, or one that returns null, 0 or false.
The rule for data access code: catch the SQLException, translate it, and rethrow with the original as the cause. Example 4 compares swallowing with translating.
} catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new DuplicateEmailException(email, e); // specific } throw new DataAccessException("Could not register " + email, e); // general, with the cause}Example 4 · Swallowing versus translating
import java.sql.SQLException;import java.sql.SQLIntegrityConstraintViolationException;
class DataAccessException extends RuntimeException { DataAccessException(String message, Throwable cause) { super(message, cause); }}
class DuplicateEmailException extends DataAccessException { DuplicateEmailException(String email, Throwable cause) { super("Email already registered: " + email, cause); }}
class SignupQueries { // Stands in for the real INSERT: this email is already in the table private int insert(String email) throws SQLException { if (email.equals("asha.rao@example.com")) { throw new SQLIntegrityConstraintViolationException( "Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'", "23000", 1062); } return 9; }
// BAD: the error disappears and the caller gets a fake id int registerSwallowing(String email) { try { return insert(email); } catch (SQLException e) { return 0; } }
// GOOD: catch, translate, rethrow with the original as the cause int register(String email) { try { return insert(email); } catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new DuplicateEmailException(email, e); } throw new DataAccessException("Could not register " + email, e); } }}
public class SwallowDemo { public static void main(String[] args) { SignupQueries queries = new SignupQueries(); String email = "asha.rao@example.com";
int id = queries.registerSwallowing(email); System.out.println("Swallowing: welcome, your customer id is " + id);
try { id = queries.register(email); System.out.println("Translating: welcome, your customer id is " + id); } catch (DuplicateEmailException e) { System.out.println("Translating: " + e.getMessage()); } }}Swallowing: welcome, your customer id is 0 Translating: Email already registered: asha.rao@example.com
What this code does
registerSwallowingcatches the duplicate-key error and returns 0. The caller happily welcomes a customer with id 0 who was never saved, and nobody ever learns why.registercatches, translates and rethrows. The caller gets a clearDuplicateEmailExceptionand can tell the user exactly what happened.insertstands in for the realINSERTand throws the same exception MySQL sent in the previous lesson.
The caller of a swallowing method works with fake data, and the real error is gone. Two common slips: throw new DataAccessException(e.getMessage()) keeps the text but drops the cause and its stack trace, and logging the same exception in every layer fills the log with duplicates. Translate once, log once, at the top.
Find the bug
Find the wrong line
Select the line that is wrong.
A failed sign-up tells the user "your customer id is 0". Which line?
Round 1 of 3Messages for users, details for logs
A user message is the short, polite text shown to the user that says what to do next. It never shows SQL, table names, stack traces or server addresses.
Show the user one short message and keep the details for the log. Example 5 prints both for a duplicate email.
Example 5 · One message for the user, details for the log
import java.sql.SQLException;
class DataAccessException extends RuntimeException { DataAccessException(String message, Throwable cause) { super(message, cause); }}
class DuplicateEmailException extends DataAccessException { DuplicateEmailException(String email, Throwable cause) { super("Email already registered: " + email, cause); }}
// A stand-in for a real logger: a real app writes these lines to a log file, not to the screenclass Log { private static int nextRef = 1001;
static String error(String what, Throwable e) { String ref = "ERR-" + nextRef++; System.out.println(" [log " + ref + "] " + what + ": " + e.getMessage()); for (Throwable t = e.getCause(); t != null; t = t.getCause()) { String detail = t instanceof SQLException s ? " (state " + s.getSQLState() + ", code " + s.getErrorCode() + ")" : ""; System.out.println(" [log " + ref + "] caused by " + t.getClass().getSimpleName() + ": " + t.getMessage() + detail); } return ref; }}
public class UserVsLogDemo { static void signUp(String email, RuntimeException failure) { System.out.println("Sign up " + email); try { throw failure; // stands in for customerQueries.register(...) } catch (DuplicateEmailException e) { System.out.println(" This email is already registered. Log in or use another email."); } catch (DataAccessException e) { String ref = Log.error("Sign up failed for " + email, e); System.out.println(" Sorry, we could not save your details right now. Please try again."); System.out.println(" (Reference: " + ref + ")"); } }
public static void main(String[] args) { SQLException duplicate = new SQLException( "Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'", "23000", 1062); signUp("asha.rao@example.com", new DuplicateEmailException("asha.rao@example.com", duplicate));
SQLException down = new SQLException("Communications link failure", "08S01", 0); signUp("kavya.reddy@example.com", new DataAccessException("Could not register kavya.reddy@example.com", down)); }}Sign up asha.rao@example.com This email is already registered. Log in or use another email. Sign up kavya.reddy@example.com [log ERR-1001] Sign up failed for kavya.reddy@example.com: Could not register kavya.reddy@example.com [log ERR-1001] caused by SQLException: Communications link failure (state 08S01, code 0) Sorry, we could not save your details right now. Please try again. (Reference: ERR-1001)
What this code does
- A duplicate email is expected, so the user gets a helpful message and nothing is logged.
- A connection failure is unexpected.
Log.errorrecords the action, the message and each cause with its SQL state and code, under a referenceERR-1001. The user sees a calm message with the same reference. - The order of the
catchblocks matters:DuplicateEmailExceptionmust come before its parentDataAccessException.
A log entry is for the developer: the action, the message, the whole cause chain with SQL state and error code, and a reference such as ERR-1001 that the user can quote. Expected situations (duplicate email, product not found) need only the user message; unexpected ones (database down, bad SQL) get both.
java.util.logging.Next step
Check your understanding
11 quick questions