Error Handling in JDBC

JDBC’s error handling model is based on Java exceptions; therefore, the standard try/catch/finally error handling paradigm of Java can be applied to JDBC applications. The following Java code fragment is an example of how to use a try / catch / finally code block to gracefully handle application exceptions and free allocated resources:

Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
   // Create and use the Connection, Statement, and ResultSet objects      
   connection = DriverManager.getConnection( connection_string );
   statement = connection.createStatement( );
   resultSet = statement.executeQuery( SQL );

} catch( Exception e ) {
   // Then, notify the user of an error.
} finally {
   if( resultSet != null ) 
      try{resultSet.close( );} catch(Exception e) {}
   if( statement != null ) 
      try{statement.close( );} catch(Exception e) {}
   if( connection != null ) 
      try{connection.close( );} catch(Exception e) {}
}

If an error occurs in the try block and an exception (of type Exception in this case) is thrown, the exception will be caught and the code in the catch block will be executed. The finally block, which will be executed regardless of whether an exception is thrown, should be responsible for freeing the resources held by the connection, result set, and statement objects. Note that each object is first tested for a null value before freeing the resources held by the object. This NULL test is to make the code applicable to all error conditions ...

Get SQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.