Export (0) Print
Expand All

Handling Exceptions

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 application block 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 re-thrown.
  • 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.

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. It assumes that you have resolved the Database class you require and stored a reference in the variable named db. For more information on instantiating objects, see Creating and Referencing Enterprise Library Objects.

DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory"); 

IDataReader reader = null;

try
{
  //...
  reader = db.ExecuteReader(cmd);
}
catch(Exception ex)
{
  // Process exception
}
finally
{
  if (reader != null)
    reader.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.

DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory"); 

using (IDataReader reader = db.ExecuteReader(cmd))
{
  // Process results
}

For design and implementation guidelines for exception management in .NET, see the Design Guidelines for Exceptions.

When you use the asynchronous versions of the Data Access Application Block methods, you may receive an error when you call the Begin version of the method. This occurs if the block detects an error before it initiates the call to the database. This includes errors commonly seen with the synchronous versions of the methods, such as invalid parameters, lack of a valid connection, or connectivity problems.

However, after execution starts, an exception cannot be raised until you execute the End version of the corresponding method. At this point, you must handle the exception in the same way as when calling any of the synchronous versions of the methods. If you are using Windows WaitHandle instances to execute operations, the return value from the WaitOne, WaitAll or WaitAny method will indicate the individual operation that failed.

For more information about asynchronous data access execution, see Asynchronous Command Execution in ADO.NET 2.0.


Show:
© 2014 Microsoft