O'Reilly logo

SQL in a Nutshell, 2nd Edition by Kevin Kline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required