Which one is Safer? Putting An "for" in a "Try" , or putting a "Try" in An "for"?

I have this piece of code, I want to know do they work likewise and only their speed is different or they act totally different?

   try
   {
     for (int i = Start; i < End; i++)
     {
         src.Samples[i].x = i;
         src.Samples[i].y = HR[i];
     }
   }
   catch{}

or

     for (int i = Start; i < End; i++)
     {
       try
       {
         src.Samples[i].x = i;
         src.Samples[i].y = HR[i];
       }
       catch
       {
         break;
       }
     }
Jon Skeet
people
quotationmark

Just don't do that to start with - it's an abuse of exceptions, IMO. Write the code so it's safe without try/catch. If you don't know whether HR is long enough, use:

int cappedEnd = Math.Min(HR.Length, End);
for (int i = Start; i < cappedEnd; i++)
{
    src.Samples[i].x = i;
    src.Samples[i].y = HR[i];
}

(Use similar logic for Start if that might be invalid.)

If you feel you absolutely have to use try/catch for some reason, I'd catch the exact type you're expecting to be thrown, and put it on the outside of the loop - catching just to break feels even worse to me. And no, I wouldn't expect any significant performance difference either way.

people

See more on this question at Stackoverflow