Solved

ADO.Net error handling

Posted on 2010-09-17
6
487 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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
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: …

759 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