Solved

ADO.Net error handling

Posted on 2010-09-17
6
488 Views
Last Modified: 2013-12-16
I am looking for some advice or guidance on catching errors when working with ADO.net and SQL server.  Most examples and books, show code like

try
{
}
catch (Exception ex)
{
}

That works fine, however, I have never liked catching "Exception".  What is the best practice when catching exceptions in regard to ADO.Net?  
0
Comment
Question by:shanemay
6 Comments
 
LVL 41

Expert Comment

by:guru_sami
ID: 33702953
you can catch provider specific exceptions like below:

try
{
  //Data access code
}
catch (SqlException sqlex) // more specific
{
}
catch (Exception ex) // less specific
{
}
finally{
 //if you are not having using construct don't forget to close connection and reader objects here
}

Check Exceptions handling here: http://msdn.microsoft.com/en-us/library/ee817654.aspx
0
 
LVL 4

Expert Comment

by:thepanch
ID: 33702965
i suggest you to throw the exception on the main class and then in the view catch it like this

public class clAlumno
{
 public DataTable ObtenerDataTableReporteAspirante(long ID_Alumno)
    {
        DataTable dt;
       
        try
        {
            oCon.OpenConnection();
            oCon.clearParameters();
            oCon.addParameter("@ID_Alumno", ID_Alumno);
            dt = oCon.getDataTableSP("ProcRptFichaAspirante");          
        }
        catch (Exception ex) { throw new Exception(ex.Message); }
        finally { oCon.CloseConnection(); }
        return dt;
    }
}

and then in the view, only do the try catch
like the code you show
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33704286

Catch exception only if you have a purpose to do something in the catch. For example:

1. Catch exception in the ui/form code - for the Purpose of: showing the error message for example in a msg box to the user.

UI Code:
private void buttonCreate_Click(...)
{
      try
      {
           da.CreateCustomer(....);
       }
       catch(Exception ex)
       {
            MessageBox.Show(ex.Message);
        }
}

2. Catch exception in non-ui code for the Purpose of: wrapping the exception in an application specific exception class and rethrow. Because there can be different types of exception in the lower layer (for example Data Access layer) and top ui layer can not expect all the types of exception; instead if the data access layer throws a common application specific custom exception (e.g. OurDataAccessException), then ui layer can specifically catch this exception.

Data Access Code:

public bool CreateCustomer(...)
{
    try
    {
          // some sql operation here
    }
    catch(SqlException sqlEx)
    {
         // wrap the SqlException in our custom exception so that higher layer code can specifically catch our exception, because higher layer sometimes wont know what are all the lower layer exceptions it can expect.
           
         throw new OurDataAccessException("Error creating customer...", sqlex );
     }

}

3. Catch exception anywhere for the purpose of logging the exception and rethrow the same exception.

    try
    {
          // some sql operation here
    }
    catch(Exception ex)
    {
         LogException(ex)
         
         throw ex; // we wanted only to log; rethrow the same exception
    }

If there is no specific purpose, then dont catch; let it go to the higher level code....

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 9

Expert Comment

by:Rahul Goel
ID: 33707595
You can use Enterprise Library in .Net Handling...and you can define the policies for the SQL Exceptions.
Using this framework you can wrap the SQL Exception or any unhandled exception into a custom Exception without wring single line of code.
http://entlib.codeplex.com 
 
0
 
LVL 13

Accepted Solution

by:
Naman Goel earned 500 total points
ID: 33707852
I am also not in favor of catching exception but we have to handle some of the sql exception like connection problems and report the same to user.

Use error code to handle different type of error which will be returned by Sql server

use this type of exception handling



try
{
// some ado.net code
}
catch(SQLException e)
{
     ReformatSQLException(e, serverName, databaseName)
}

 /// <summary>
    /// Class for Custom exception messages
    /// </summary>
	public class CustomException : Exception
	{
		public string Details { get; private set; }

		public CustomException(string customMessage, string details) :
			base(customMessage)
		{
			Details = details;
		}

	}

	public static Exception ReformatSQLException(SqlException sqlException, string serverName, string repositoryName)
		{
			string customMessage = String.Empty;

			switch (sqlException.Number)
			{
				case SqlExcepetionNumbers.CannotOpenDB:
					customMessage = String.Format(!String.IsNullOrEmpty(repositoryName) ? Localized.CannotOpenDB : Localized.CannotOpenDB2, serverName, repositoryName);
					break;

				case SqlExcepetionNumbers.NetworkDown:
				case SqlExcepetionNumbers.NetworkDown2:
				case SqlExcepetionNumbers.NetworkDown3:
				case SqlExcepetionNumbers.SemaphorError:
					customMessage = String.Format(!String.IsNullOrEmpty(repositoryName) ? Localized.SqlServerNetworkDown : Localized.SqlServerNetworkDown2, serverName, repositoryName);
					break;

				case SqlExcepetionNumbers.SqlServerServiceStopped:
					customMessage = String.Format(!String.IsNullOrEmpty(repositoryName) ? Localized.SqlSeverServiceDown : Localized.SqlSeverServiceDown2, serverName, repositoryName);
					break;

				case SqlExcepetionNumbers.SqlServerServicePaused:
					customMessage = String.Format(Localized.SqlServerServicePaused, serverName);
					break;

				case SqlExcepetionNumbers.LoginFailureDomainController:
					customMessage = String.Format(!String.IsNullOrEmpty(repositoryName) ? Localized.DomainControllerCannotBeReached : Localized.DomainControllerCannotBeReached2, serverName, repositoryName);
					break;

				case SqlExcepetionNumbers.ConnectionTimeout:
					customMessage = String.Format(!String.IsNullOrEmpty(repositoryName) ? Localized.ConnectionTimeOutExpired : Localized.ConnectionTimeOutExpired2, serverName, repositoryName);
					break;

				case SqlExcepetionNumbers.AccessDenied:
				case SqlExcepetionNumbers.LoginFailure:
					customMessage = String.Format(!String.IsNullOrEmpty(repositoryName) ? Localized.SqlServerAccessDenied : Localized.SqlServerAccessDenied2, serverName, repositoryName);
					break;

				case SqlExcepetionNumbers.TransportLevelError:
				case SqlExcepetionNumbers.TransportLevelError2:
					customMessage = String.Format(!String.IsNullOrEmpty(repositoryName) ? Localized.SqlServerTransportLevelError : Localized.SqlServerTransportLevelError2, serverName, repositoryName);
					break;

				case SqlExcepetionNumbers.MSDTCUnavailable:
					customMessage = String.Format(Localized.SqlServerMSDTCError, serverName);
					break;

				case SqlExcepetionNumbers.LinkedServerError:
					customMessage = String.Format(Localized.SqlServerLinkedServerError, serverName);
					break;
			}

			if (customMessage == String.Empty)
			{
				return sqlException;
			}

			return new CustomException(customMessage, sqlException.Message + Environment.NewLine + sqlException.StackTrace);
		}

Open in new window

0
 

Author Closing Comment

by:shanemay
ID: 33715957
Thank you for your help.  It is greatly appreciated.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
Delivering innovative fully-managed cloud services for mission-critical applications requires expertise in multiple areas plus vision and commitment. Meet a few of the people behind the quality services of Concerto.

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now