Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

SQLException — diagnosing JDBC errors

SQLException describes database-access errors in JDBC. It exposes a message, SQLState, vendor code, cause, and a chain of additional exceptions.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new SQLException(String reason, String sqlState, int vendorCode, Throwable cause)

SQLException in java.sql extends Exception: it is a checked exception that must be caught or declared with throws. It can occur when establishing a connection or executing a JDBC query, not just for invalid SQL syntax.

getMessage() returns a description, getSQLState() a code following XOPEN or SQL:2003 conventions, and getErrorCode() a vendor-specific code. Do not confuse these two codes. The message-only constructor initializes SQLState to null and the vendor code to 0.

getCause() describes the cause; getNextException() exposes a separate diagnostic chain ending in null. setNextException() appends an exception to that chain. Iteration with for (Throwable item : ex) includes causes as well, not only SQLException objects.

The example deliberately creates and catches an exception without a database or driver. The value 101 is a demonstration vendor code, not a portable JDBC code.

Examples

import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        SQLException first = new SQLException("Demo failure", "42000", 101);
        first.setNextException(new SQLException("Extra detail"));

        try {
            throw first;
        } catch (SQLException ex) {
            for (SQLException current = ex; current != null;
                    current = current.getNextException()) {
                System.out.println(current.getMessage() + " | "
                        + current.getSQLState() + " | "
                        + current.getErrorCode());
            }
        }
    }
}

Result

Demo failure | 42000 | 101
Extra detail | null | 0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources