User Guide

Table Of Contents
190 Chapter 9: Writing and Calling User-Defined Functions
Using exceptions
UDFs written in CFScript can handle exceptions using the
try and catch statements. UDFs
written using the
cffunction tag can use the cftry, cfcatch, cfthrow, and cfrethrow tags.
Using exceptions corresponds to the way many functions in other programming languages handle
errors, and can be an effective way to handle errors. In particular, it separates the functional code
from the error-handling code, and it can be more efficient than other methods at runtime,
because it does not require testing and branching.
Exceptions in UDFs have the following two dimensions:
Handling exceptions generated by running the UDF code
Generating exceptions when the UDF identifies invalid data or other conditions that would
cause errors if processing continued
Handling exceptions in UDFs
A UDF should use try/catch blocks to handle exceptions in the same conditions that any other
ColdFusion application uses try/catch blocks. These are typically circumstances where the
function uses an external resource, such as a Java, COM, or CORBA object, a database, or a file.
When possible, your application should prevent, rather than catch, exceptions caused by invalid
application data. For example, the application should prevent users from entering a zero value for
a form field that is used to divide another number, rather than handling exceptions generated by
dividing by zero.
When ColdFusion catches an exception, the function can use any of the following methods to
handle the exception:
If the error is recoverable (for example, if the problem is a database timeout where a retry might
resolve the issue), try to recover from the problem.
Display a message, as described in “Displaying error messages” on page 186.
Return an error status, as described in “Providing status information” on page 187.
<cfif myInterest EQ -1>
<cfoutput>
ERROR: #status.errorMsg#<br>
</cfoutput>
If the function returns -1, there must be an error.
Displays the message that the function placed in the
status.errorMsg structure key.
<cfelse>
<cfoutput>
Loan amount: #Form.Principal#<br>
Annual percentage rate:
#Form.AnnualPercent#<br>
Loan duration: #Form.Months#
months<br>
TOTAL INTEREST: #myInterst#<br>
</cfoutput>
</cfif>
If the function does not return -1, it returns an interest
value. Displays the input values and the function
return value.
Code Description