Error and Exception Handling

New in ColdFusion MX is the ability to trap errors and exceptions within CFScript code using try/catch statements similar to the cftry and cfcatch tags described in Chapter 9. If you were writing exception-handling code using the cftry and cfcatch tags, it might look something like the code in Example 19-20.

Example 19-20. Exception handling with cftry and cfcatch

<cftry>
  <cfset x=y+1>
  
  <cfcatch type="Expression">
    <cfoutput>
    Expression Error: #cfcatch.Message#
    </cfoutput>
  </cfcatch>
   
  <cfcatch type="Any">
    <cfoutput>
    General Error: #cfcatch.Message#
    </cfoutput>
  </cfcatch>
</cftry>

This code attempts to set the variable x equal to y+1. It then includes cfcatch code for handling Expression type errors, and another cfcatch block for catching Any exception that is not caught by the Expression type. In this case, the exception handling comes in the form of a semi-custom error message written to the browser.

The same code rewritten in CFScript is shown in Example 19-21.

Example 19-21. Exception handling with try and catch in CFScript

<cfscript>
try {
  x=y+1;
}
   
  catch("Expression" exception) {
    writeOutput("Expression Error: " & exception.Message);
  }
   
  catch("Any" exception) {
    writeOutput("General Error: " & exception.Message);
  }
</cfscript>

The CFScript equivalent try/catch code is slightly different than the tag-based version. In CFScript, catch statements do not need to be nested in the try code as cfcatch statements do in an equivalent cftry tag. The syntax for ...

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.