Why Use cftry and cfcatch?

Someone on a mailing list asked today for an explanation of cftry and cfcatch, and examples of when to use them. Although I don’t think it ever made it to the list (the server seems to be down), this was my response:

I have found the try/catch framework to be most useful in two circumstances:

  1. When your code could encounter an error that you either expect or can recover from, you can trap and handle it with cftry and cfcatch. For instance, I wrote some code recently that checks if a specific file exists on the file system. If it does, the file gets included, but if it doesn’t exist, I just include another file that I know will exist. I put a cftry and cfcatch around the include code to accomplish this.
  2. If you want to add more information to an error. At any particular point in your code, you usually know more about the code than the CF server would if it were to throw an error at that particular point. Usually, that’s fine because the chance of an error being thrown is very small, or the additional information you have would not necessarily be useful in fixing the error, however sometimes you might want to include this additional information in the even of an error. For instance, if you are trying to include a page with a URL from a database, rather than just hoping that the page exists or letting ColdFusion formulate an error message if it is not there, you might wrap your cfinclude in a try/catch block, then re-throw the error (assuming you have no way to recover from it) with an additional message explaining that the URL that was retrieved from the database (might even include database information like the data source and the query) is out of synch with the file system.

Comments are closed.