1

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; } } 

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - For your last sentence about when not to throw exceptions.
6

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.

1 Comment

+1 Yup...Eric's hanging out here on the C# tagged questions again :)
3

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.

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.