We help IT Professionals succeed at work.

Try-Catch within Catch Exception handler C# .NET2005

Medium Priority
425 Views
Last Modified: 2012-05-11
Hello Experts,

Is it a god Practice to this:
 
I tried this:

catch (System.Data.SqlClient.SqlException sqlEx)
{

try
{
if (sqlEx.Class == 14 && sqlEx.Number == 2627)
    {
        //Duplicate Record
        return 1;
    }

     throw sqlEx;
}
catch (Exception ex) {
 }

}

It works, is it a good way of programming....

Open in new window


Since, I cannot use finally here.Because it will execute always...
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
That example doesn't make much sense. Why would you wrap integer comparison in a try/catch?
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
No, it is not a good programming practice.  Try/Catches can be costly and you want to use them sparingly.  Instead, use a conditional statement.
AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
It works - are you certain?

try
{
if (sqlEx.Class == 14 && sqlEx.Number == 2627)
    {
        //Duplicate Record
        return 1;
    }

     throw sqlEx;   <<------------------ A
}
catch (Exception ex) {  <<---------------- B
 }


I am not 100% certain but I would expect the line A to be caught by B, if so then I don't think that is what you wanted.

Author

Commented:
Below is the exact code:
Public int Test()
{ 

try
{
..............

return 1;
}

catch (System.Data.SqlClient.SqlException sqlEx)
{

try
{
if (sqlEx.Class == 14 && sqlEx.Number == 2627)
    {
        //Duplicate Record
        return 1;
    }

     throw sqlEx;
}
catch (Exception ex)
 {
   return 0;
 }

}
}

Open in new window



I want to catch an exception, if it is an SQLException(like duplicate Insert), I return as value 1. If it is other exception I " throw" the exception and catch in the another exception Block.


My point here is "Having Try-Catch withing Catch statement" is a good practice to do.  

Author

Commented:
Thanks.
AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
I've got around to testing.
My comment #35435274 is relevant.
What you are doing does NOT work the way you expect it to do, what you have accepted as an answer does not cure your original problem.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.