Home » Tutorials » ColdFusion » Try and Catch Statement

Try and Catch Statement

ColdFusion provides a try and catch statement to deal with error handling. Basically, a try and catch statement attempts some code. If the code fails, ColdFusion will do whatever is in the exception to try to handle it without breaking and spitting out an error message to the screen. Of course, many different types of exceptions can occur, which should sometimes be handled in a different manner than the others. Let’s take a look at the general syntax of a try and catch statement in ColdFusion.

Example
<cftry>

  <!—Code tried —>
  <cfcatch type=”Exception_Type”>

    <!—Code executed when the code above fails—>
  </cfcatch>
</cftry>

So, we can see that it isn’t very complicated. You simply have a try and a catch. In the try, you attempt the code that might fail. The catch code is only triggered when that happens. The idea for the catch code is to handle the error and not just to stop ColdFusion from showing an error message. You actually want to correct something in the catch statement.

When to use a try/catch statement

Some people don’t want to use try/catch. They think that if there is a chance the code might not work, they shouldn’t use the code at all. So, what are a couple of examples of why this would be useful? Let’s say you have some code that updates a database with extremely important information for your manager. So, if that code fails your manager would never get any of the information derived from that code. However, if you would have used a try and catch statement, you could have made ColdFusion send an email with the information whenever it failed. This would let your manager have information that he wouldn’t have without this powerful little function. You can also use try and catch to improve the exception reporting from ColdFusion. A custom message from the web developer is usually better than a default error message.



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Try and Catch Statement". After Hours Programming. Accessed on March 16, 2024. https://www.afterhoursprogramming.com/tutorial/coldfusion/try-and-catch-statement/.

  • Stewart, Suzy. "Try and Catch Statement". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/coldfusion/try-and-catch-statement/. Accessed 16 March, 2024.

  • Stewart, Suzy. Try and Catch Statement. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/coldfusion/try-and-catch-statement/.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.