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

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.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *

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