Handling Exceptions

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

Strategies for handling exceptions are essential in any enterprise application. The following information will help you incorporate the Data Access Application Block into your approach to managing exceptions:

  • The CreateDatabase method uses configuration information, which may result in configuration-related exceptions.
  • The Database methods use both ADO.NET and the underlying database provider. Exceptions thrown by ADO.NET are caught by the Data Access Application Block for instrumentation purposes, and then they are rethrown.
  • Adequately processing an exception often requires access to the specific exception type. You can include a catch statement for a specific database provider exception such as SqlException. However, database provider–specific exception types are not portable across different providers.

Use CommandBehavior.CloseConnection to call ExecuteReader. This closes the connection when the DataReader is closed. If you use ExecuteReader within a try block, you should add a finally statement and close the returned DataReader object, as shown in the following example.

Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory"); 

IDataReader dataReader = null;

try
{
  //...
  dataReader = db.ExecuteReader(dbCommand);
}
catch(Exception ex)
{
  // Process exception
}
finally
{
  if (dataReader != null)
    dataReader.Close();
}

Alternatively, you can include the using statement to dispose of the DataReader object, which causes it to close, as shown in the following example.

Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory"); 

using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
    // Process results
}

For design and implementation guidelines for exception management in .NET, see the Exception Management Architecture Guide.

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.
Show: