Try/catch code rules and recommendations

Follow these rules and recommendations when you use cftry and cfcatch tags:

  • The cfcatch tags must follow all other code in a cftry tag body.

  • You can nest cftry blocks. For example, the following structure is valid:

    <cftry> 
        code that may cause an exception 
        <cfcatch ...> 
            <cftry> 
                First level of exception handling code 
                <cfcatch ...> 
                    Second level of exception handling code 
                </cfcatch 
            </cftry> 
        </cfcatch> 
    </cftry>

    If an exception occurs in the first level of exception-handling code, the inner cfcatch block can catch and handle it. (An exception in a cfcatch block cannot be handled by cfcatch blocks at the same level as that block.)

  • ColdFusion always responds to the latest exception that gets raised. For example, if code in a cftry block causes an exception that gets handled by a cfcatch block, and the cfcatch block causes an exception that has no handler, ColdFusion displays the default error message for the exception in the cfcatch block, and you are not notified of the original exception.

  • If an exception occurs when the current tag is nested inside other tags, the CFML processor checks the entire stack of open tags until it finds a suitable cftry/cfcatch combination or reaches the end of the stack.

  • Use cftry with cfcatch to handle exceptions based on their point of origin within an application page, or based on diagnostic information.

  • The entire cftry tag, including all its cfcatch tags, must be on a single ColdFusion page. You cannot place the <cftry> start tag on one page and have the </cftry> end tag on another page.

  • For cases when a cfcatch block is not able to successfully handle an error, consider using the cfrethrow tag, as described in Using the cfrethrow tag.

  • If an exception can be safely ignored, use a cfcatch tag with no body; for example:

    <cfcatch Type = Database />
  • In problematic cases, enclose an exception-prone tag in a specialized combination of cftry and cfcatch tags to immediately isolate the tag's exceptions.