Click here to Skip to main content
15,922,894 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to catch the system generated unique key exception and I want to throw my own message.

I am doing it in Visual Studio 2008

I am using the following code. In my application code just before inserting i am using this code.

VB
Try
            l_Database.gp_BeginTransaction()
            ls_SqlStr = "SELECT * FROM  mst_country where cn_sid = po_Country.cn_sid"

        Catch ex As SqlException
            Throw ex
        Finally
            l_Database.gp_CloseConnection()
            l_Database = Nothing
        End Try


And in my business logic layer I am trying to write my own message by calling this exception.

But I am not sure whether I am doing correctly or not.

Please can any body suggest me to fix this and work efficiently.

Regards
Srikar
Posted
Updated 8-Dec-09 10:59am
v2

1 solution

Hi,

Please avoid catching and throwing it.
If you any logics inside catch, then its fine.
Just catching and throwing the exception back doesn't add a value
and tis expensive too..

Instead think of the following code:

Try
l_Database.gp_BeginTransaction()
ls_SqlStr = "SELECT * FROM mst_country where cn_sid = po_Country.cn_sid"

Finally
l_Database.gp_CloseConnection()
l_Database = Nothing
End Try

Here the catch block is removed and the same is handled in the business logic layer..

Your business logic layer looks like:

try
{
//call the funtion above..
}
catch(SqlException ex)
{
bool hasOtherErrors = false;
//The batch statments will have a collection of errors and there are possibilites
//where you will get other errors like foriegn key..In that case you should throw the
//error back if its not a unique constratint error.
foreach(SqlError er in ex.Errors)
{
//parse each and every sqlerror and identify if its a unique contraint error.
if(er.ErrorNumber == UNIQUE_CONSTRAINT_ERROR_NO)
{
//show your customized error message here....
}
else
{
//If it has any other error other than a UniqueConstraint error..
hasOtherErrors = true;
}
}//for each

if(hasOtherErrors)
{
//rethrow the error since we have other errors in the bathc statement
//Also use throw to preserve stack trace
throw;
}
}//cathc
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900