List and explain three kinds of exceptions raised in JDBC

Three Kinds of Exceptions Raised in JDBC

In JDBC (Java Database Connectivity), exceptions are used to handle errors that occur during database operations. All JDBC exceptions are subclasses of the java.sql.SQLException class.

Here are three common types of JDBC exceptions:


1. SQLException

Description:

  • This is the base exception class for JDBC errors.
  • Thrown when a database access error occurs, such as:
    • Wrong SQL syntax
    • Accessing a non-existent table
    • Connection issues

Example:

try {
    Statement stmt = con.createStatement();
    stmt.executeUpdate("SELECT * FROM invalid_table"); // Table doesn't exist
} catch (SQLException e) {
    System.out.println("SQLException: " + e.getMessage());
}

Common Methods:

  • getMessage() – Error message
  • getSQLState() – SQL state code
  • getErrorCode() – Vendor-specific error code

2. SQLSyntaxErrorException

Description:

  • Subclass of SQLException.
  • Thrown when there is a syntax error in the SQL statement.

Example:

try {
    Statement stmt = con.createStatement();
    stmt.executeUpdate("SELEC * FROM users"); // Typo: SELEC instead of SELECT
} catch (SQLSyntaxErrorException e) {
    System.out.println("Syntax Error: " + e.getMessage());
}

When it occurs:

  • Misspelled SQL keywords
  • Missing commas, quotes, or wrong clause structure

3. SQLTimeoutException

Description:

  • Thrown when a timeout occurs while attempting to:
    • Connect to the database
    • Execute a query
  • Useful to avoid hanging the application during long or blocked operations.

Example:

try {
    DriverManager.setLoginTimeout(5); // Timeout in seconds
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "user", "pass");
} catch (SQLTimeoutException e) {
    System.out.println("Connection timed out: " + e.getMessage());
}

Summary Table

Exception TypeDescriptionWhen It Occurs
SQLExceptionGeneral DB access errorWrong table name, invalid query, etc.
SQLSyntaxErrorExceptionSQL syntax is invalidMisspelled SQL keywords
SQLTimeoutExceptionOperation takes too longConnection or query timeout

Leave a Reply

Your email address will not be published. Required fields are marked *