Saturday, 4 February 2012

Continue in cfloop


Have you ever used continue in cfloop without cfcontinue/cfbreak.

Check this code:

Here I have a <cfloop> which runs 10 times for value of 'i'. I want to implement continue tag if the 'i' is an even no. To achieve that check if the no.is even and if it is, I throw a custom error.

The good thing is that you can always catch this error. So Catch this error before closing </cfloop> tag. Though you can add some code over there also but it totally depends on you. For a normal continue you need not add anything in <cfcatch> block. As expected this thrown error wil be caugth in <cfcatch> and it will proceed for next iteration in <cfloop>, without any error. And this is how it behaved as continue.

So all in all you need to remember that

  • instead of continue you can throw a custom error
  • catch this error in the end (before closing </cfloop> tag)
  • Do nothing in <cfcatch> tag (though its your wish but its not necessary)
  • close </cfloop> tag.

Hope you got this.
Cheers!!!

4 comments:

  1. I use cfcontinue inside cfloop all the time.

    http://cfdocs.org/cfcontinue

    As that page points out, it exists since ACF9 - though it has been available in both OpenBD and Railo for ages.

    ReplyDelete
  2. I'm not sure this would be a great idea, if you are looping for anything other than a small number of iterations. Cftry/catch can be expensive.

    Also, CF9 introduced a cfcontinue tag, its one of my favorite language additions!

    ReplyDelete
  3. What happens if you're looping through query results and you use cfcontinue on the last loop? Does CF automatically exit the loop or will it loop beyond the limit of the query to infinity?

    ReplyDelete
  4. you are right, this method can be used before CF9. But try/catch is always expensive and make lose performance all the time in every language.

    ReplyDelete