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 messagegetSQLState()
– SQL state codegetErrorCode()
– 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 Type | Description | When It Occurs |
---|---|---|
SQLException | General DB access error | Wrong table name, invalid query, etc. |
SQLSyntaxErrorException | SQL syntax is invalid | Misspelled SQL keywords |
SQLTimeoutException | Operation takes too long | Connection or query timeout |