User Guide

Table Of Contents
186 Chapter 9: Writing and Calling User-Defined Functions
As with many programming practice, there are valid exceptions to this recommendation. For
example you might do any of the following:
Use a shared scope variable, such as an Application or Session scope counter variable.
Use the Request scope to store variables used in the function, as shown in “Using the Request
scope for static variables and constants” on page 196.).
Create context-specific functions that work directly with caller data if you always synchronize
variable names.
Note: If your function must directly change a simple variable in the caller (one that is not passed to the
function by reference), you can place the variable inside a structure argument.
Using arguments
Function arguments can have the same names, but different values, as variables in the caller.
Avoid such uses for clarity, however.
The following rules apply to argument persistence:
Because simple variable and array arguments are passed by value, their names and values exist
only while the function executes.
Because structures, queries, and objects such as COM objects are passed by reference, the
argument name exists only while the function executes, but the underlying data persists after
the function returns and can be accessed by using the callers variable name. The caller’s
variable name and the argument name can, and should, be different.
Note: If a function must use a variable from another scope that has the same name as a function-only
variable, prefix the external variable with its scope identifier, such as Variables or Form. (However,
remember that using variables from other scopes directly in your code is often poor practice.)
Handling errors in UDFs
This section discusses the following topics:
Displaying error messages directly in the function
Returning function status information to the calling page
Using try/catch or cftry/cfcatch blocks and the cfthrow and cfrethrow tags to handle
and generate exceptions
The technique you use depends on the circumstances of your function and application and on
your preferred programming style. However, most functions should use the second or third
technique, or a combination of the two. The following sections discuss the uses, advantages, and
disadvantages of each technique, and provide examples of their use.
Displaying error messages
Your function can test for errors and use the
WriteOutput function to display an error message
directly to the user. This method is particularly useful for providing immediate feedback to users
for simple input errors. You can use it independently or in conjunction with either of the other
two error-handling methods.