
288
DEVELOPING
COLDFUSION 9 APPLICATIONS
Developing CFML Applications
Las
t
upda
te
d 8/5/2010
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 e-mail address so the company staff can enter the data 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:
Содержание COLDFUSION 9
Страница 1: ...Developing Applications ADOBE COLDFUSION 9...