tags:

views:

170

answers:

4

I am curious to know if I should minimize the code that goes inside a try/catch block or it really does not matters.

   public bool ObjectExists(string stringTest, string againSomethingElse)
    {
        if(true) {}
        else {} //Code here is better/worst/same
        try
        {
            //Versus code inside try/catch block

        }
        catch (Exception)
        {

            throw;
        }
    }
+9  A: 

In .net, try/catch only incurs an overhead if an exception is actually thrown. So don't worry too much about the performance implications of having code inside the try. Just don't throw exceptions as a form of flow control.

recursive
+1 - For your last sentence about when not to throw exceptions.
James Black
+2  A: 

I agree with recursive, but you may want to look at a nice explanation: http://www.programmersheaven.com/user/pheaven/blog/175-Do-trycatch-blocks-hurt-runtime-performance/

Basically, there is no problem using try..catch, but, I tend to limit what I have in them as I think it is bad practice to depend on them rather than doing what you can to ensure exceptions aren't thrown, as exceptions will be expensive, so, check that that string is not null before getting the length of it.

James Black
+2  A: 

I agree with the above but you shouldn't put your entire code block in a try catch and let it catch a formatexception or null reference. You should write code for these and handle them on your own.

I don't know how many times I've seen:

try {
 Request.QueryString["id"].ToString();
}

Obviously a null reference if id is null, so check if it's null, don't try/catch it.

Jack Marchetti
+6  A: 

Here's the right way to approach this problem.

First write the code so that the exception handling is CORRECT. Always correctness first.

Then set reasonable, customer-focussed performance goals. Then test your program. Then, if you haven't met your goals, use a profiler to find the slowest thing. If the slowest thing by some bizarre coincidence happens to be your correct exception handling, only then should you even consider what the performance cost of exception handling is.

Eric Lippert
+1 - Early optimization = evil!
Jason Down
+1 Yup...Eric's hanging out here on the C# tagged questions again :)
Abhijeet Patel
Well, *yeah*. -
Eric Lippert