Domi.Zhang
Domi.Zhang

Reputation: 1705

Why should I put try/catch block out of loop?

Here is CodeReview Guideline by Practice&Patterns team.http://msdn.microsoft.com/zh-cn/library/ms998574#scalenetchapt13_topic7(The link navigate to the Exception section automaticly.)

They said you should put try/catch block out of loop when you handle exception, I want to know why?

Upvotes: 13

Views: 8523

Answers (4)

to StackOverflow
to StackOverflow

Reputation: 124766

A try/catch inside a loop behaves differently from one outside the loop, unless it always rethrows the exception.

Therefore your choice will depend on your requirements: if you want to continue looping, then catch inside the loop, otherwise outside.

I think the reason for the recommendation is that try/catch inside a loop looks suspiciously like using exceptions for control flow. It's flagging a potential "code smell" rather than stating a hard and fast rule.

But it's reasonable to ignore the recommendation if that's what your requirements dictate. To take a simple but obsolete example, in a world without Int32.TryParse (.NET 1.x wasn't that long ago!), it would be reasonable to have a loop that parses a list of strings into integers using Int32.Parse in a try/catch inside the loop.

Upvotes: 2

kevchadders
kevchadders

Reputation: 8335

Due to the potential for multiple exceptions appearing in the loop which causes unnecessary overheads in your application.

If there is an error found within there then handling outside the loop makes more sense.

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263077

Because the underlying implementation of a try... catch block adds overhead to the generated code, and putting that overhead in a tight loop is not a good idea, performance-wise.

Technically, if all the iterations of your loop are "equal", and the loop should stop as soon as an exception occurs, then it's better to put the try... catch block outside of the loop. If the loop must continue despite exceptions occurring, you'll be forced to put the block inside the loop, but you might want to review your design in that case.

Upvotes: 18

Oded
Oded

Reputation: 499212

Exceptions are expensive - if you put the exception logic within a loop you risk having exceptions being thrown for every iteration in the loop. This can easily cause performance issues.

If you put the try/catch block outside of the loop, you will only need to handle a single exception.

Upvotes: 11

Related Questions