Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

ADO.Net error handling

Posted on 2010-09-17
6
Medium Priority
?
498 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
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
LVL 9

Expert Comment

by:Rahul Goel ITIL
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 2000 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses

877 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