Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

JDBC · Lesson 11

Exception Handling in JDBC

Understanding JDBC Failures

JDBC operations can fail because of invalid SQL, unavailable databases, constraint violations, timeouts, or transaction conflicts. SQLException includes vendor codes and SQL state values that help classify the failure. Good handling preserves the original cause while exposing a useful domain-level result.

Translating an Exception

Catch low-level exceptions at a boundary where the application can decide whether to retry, report a conflict, or return a server error. Never hide the original exception context.

import java.sql.SQLException;

public class DatabaseErrorMapper {
    public String classify(SQLException failure) {
        String sqlState = failure.getSQLState();
        if (sqlState != null && sqlState.startsWith("23")) {
            return "constraint-violation";
        }
        if (sqlState != null && sqlState.startsWith("08")) {
            return "connection-failure";
        }
        return "database-error";
    }
}

Failure Categories

FailureExample responseRetry?
Constraint violationValidation or conflictUsually no
Connection failureTemporary service errorSometimes
TimeoutCapacity or slow query issueCarefully
Syntax errorDeployment or code defectNo until fixed

Common Mistake and Practices

Common Mistake: Returning SQLException.getMessage() directly to an API client. Database messages may contain table names, SQL text, or infrastructure details that should stay in protected logs.

  • Log the exception with a correlation identifier.
  • Preserve the cause when wrapping exceptions.
  • Roll back failed transactions.
  • Retry only known transient failures.
  • Return stable domain or API error codes.

Real-World Use Case

A registration service maps a unique-email constraint to a friendly conflict response while logging the SQL state for operators. A lost connection becomes a temporary service error rather than a confusing raw database message.

Quiz Check

Quick Knowledge Test

Loading quiz questions...