Basic Exception Handling

Exception handling allows you to test for and trap exceptions when they happen, so that your applications can respond to problems appropriately, as opposed to just throwing an error or invoking a separate error-handling template. With exception handling, it is usually possible to allow your application to continue functioning despite the fact that an exception has occurred.

Basic exception handling in ColdFusion uses two tags, cftry and cfcatch. These tags allow you to identify potentially problematic areas of your application code and deal with anticipated exceptions where they are most likely to occur. The basic syntax for using cftry/cfcatch is:

<cftry>
Potentially problematic code...
   
  <cfcatch type="exception_type">
  Code to implement in the event the exception is caught...
  </cfcatch>
   
  <cfcatch type="exception_type">
  ...
  </cfcatch>
   
</cftry>

The cftry/cfcatch syntax is straightforward. First, you wrap the section of code for which you wish to provide exception handling by a set of cftry tags. Immediately following the potentially problematic code, you use one or more cfcatch blocks to test for various types of exceptions. This means that you can protect individual sections of your code from more than one exception at a time. Within a cfcatch block, you can include any HTML and CFML you want, including cfcatch variables (which we’ll cover in just a few moments). It is also possible to nest additional cftry/cfcatch tags within a cfcatch block for.

Let’s consider ...

Get Programming ColdFusion MX, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.