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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access