Adobe ColdFusion 8

Using cftry and cfcatch tags

The cftry tag lets you go beyond reporting error data to the user:

  • You can include code that recovers from errors so your application can continue processing without alerting the user.
  • You can create customized error messages that apply to the specific code that causes the error.

For example, you can use cftry to catch errors in code that enters data from a user registration form to a database. The cfcatch code could do the following:

  1. Retry the query, so the operation succeeds if the resource was only temporarily unavailable.
  2. If the retries fail:
    • Display a custom message to the user
    • Post the data to an email address so the data could be entered by company staff after the problem has been solved.

Code that accesses external resources such as databases, files, or LDAP servers where resource availability is not guaranteed is a good candidate for using try/catch blocks.

Try/catch code structure

In order for your code to directly handle an exception, the tags in question must appear within a cftry block. It is a good idea to enclose an entire application page in a cftry block. You then follow the cftry block with cfcatch blocks, which respond to potential errors. When an exception occurs within the cftry block, processing is thrown to the cfcatch block for that type of exception.

Here is an outline for using cftry and cfcatch to handle errors:

<cftry>
    Put your application code here ...
    <cfcatch type="exception type1">
        Add exception processing code here ...
    </cfcatch>
    <cfcatch type="exception type2">
        Add exception processing code here ...
    </cfcatch>
    ...
    <cfcatch type="Any">
        Add exception processing code appropriate for all other exceptions here ...
    </cfcatch>
</cftry>

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 will display the default error message for the exception in the cfcatch block, and you will not be 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 put 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 />

  1. In particularly problematic cases, you might enclose an exception-prone tag in a specialized combination of cftry and cfcatch tags to immediately isolate the tag's exceptions.

Exception information in cfcatch blocks

Within the body of a cfcatch tag, the active exception's properties are available in a cfcatch object. The following sections describe the object contents.

Standard cfcatch variables

The following table describes the variables that are available in most cfcatch blocks:

Property variable

Description

cfcatch.Detail

A detailed message from the CFML compiler. This message, which can contain HTML formatting, can help to determine which tag threw the exception.

The cfcatch.Detail value is available in the CFScript catch statement as the exceptionVariable parameter.

cfcatch.ErrorCode

The cfthrow tag can supply a value for this code through the errorCode attribute. For Type="Database", cfcatch.ErrorCode has the same value as cfcatch.SQLState.

Otherwise, the value of cfcatch.ErrorCode is the empty string.

cfcatch.ExtendedInf o

Custom error message information. This is returned only to cfcatch tags for which the type attribute is Application or a custom type.

Otherwise, the value of cfcatch.ExtendedInfo is the empty string.

cfcatch.Message

The exception's default diagnostic message, if one was provided. If no diagnostic message is available, this is an empty string.

The cfcatch.Message value is included in the value of the CFScript catch statement exceptionVariable parameter.

cfcatch.RootCause

The Java servlet exception reported by the JVM as the cause of the "root cause" of the exception.

cfcatch.TagContext

An array of structures structure containing information for each tag in the tag stack The tag stack consists of each tag that is currently open.

cfcatch.Type

The exception's type, returned as a string.

Note: If you use the cfdump tag to display the cfcatch variable, the display does not include variables that do not have values.

The cfcatch.TagContext variable contains an array of tag information structures. Each structure represents one level of the active tag context at the time when ColdFusion detected the exception. That is, there is one structure for each tag that is open at the time of the exception. For example, if the exception occurs in a tag on a custom tag page, the tag context displays information about the called custom tag and the tag in which the error occurs.

The structure at position 1 in the array represents the currently executing tag at the time the exception was detected. The structure at position ArrayLen(cfcatch.tagContext) represents the initial tag in the stack of tags that were executing when the compiler detected the exception.

The following table lists the tagContext structure attributes:

Entry

Description

Column

Obsolete (retained for backwards compatibility). Always 0.

ID

The tag in which the exception occurred. Exceptions in CFScript are indicated by two question marks (??). All custom tags, including those called directly, are identified as cfmodule.

Line

The line on the page in which the tag is located.

Raw_Trace

The raw Java stack trace for the error.

Template

The pathname of the application page that contains the tag.

Type

The type of page; it is always a ColdFusion page.

Database exceptions

The following additional variables are available whenever the exception type is database:

Property variable

Description

cfcatch.NativeErrorCode

The native error code associated with this exception. Database drivers typically provide error codes to assist in the diagnosis of failing database operations. The values assumed by cfcatch.NativeErrorCode are driver-dependent.

If no error code is provided, the value of cfcatch.nativeErrorCode is -1. The value is 0 for queries of queries.

cfcatch.SQLState

The SQLState code associated with this exception. Database drivers typically provide error codes to assist in the diagnosis of failing database operations. SQLState codes are more consistent across database systems than native error codes.

If the driver does not provide an SQLState value, the value of cfcatch.SQLState is -1.

cfcatch.Sql

The SQL statement sent to the data source.

cfcatch.queryError

The error message as reported by the database driver.

cfcatch.where

If the query uses the cfqueryparam tag, query parameter name-value pairs.

Expression exceptions

The following variable is only available for Expression exceptions:

Property variable

Description

cfcatch.ErrNumber

An internal expression error number, valid only when type="Expression".

Locking exceptions

The following additional information is available for exceptions related to errors that occur in cflock tags:

Property variable

Description

cfcatch.lockName

The name of the affected lock. This is set to "anonymous" if the lock name is unknown.

cfcatch.lockOperation

The operation that failed. This is set to "unknown" if the failed operation is unknown.

Missing include exceptions

The following additional variable is available if the error is caused by a missing file specified by a cfinclude tag:

Property variable

Description

cfcatch.missingFileName

The name of the missing file.