Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 561
Domi.Zhang Avatar asked Oct 28 '11 10:10

Domi.Zhang


4 Answers

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.

like image 92
Oded Avatar answered Nov 20 '22 07:11

Oded


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.

like image 20
Frédéric Hamidi Avatar answered Nov 20 '22 07:11

Frédéric Hamidi


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.

like image 2
Joe Avatar answered Nov 20 '22 09:11

Joe


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.

like image 1
kevchadders Avatar answered Nov 20 '22 09:11

kevchadders