What is the use of cftry / cfcatch? And How useful is it?
Filed under ColdFusion
Without looking into what cftry actually does, the first thought that popped into my head was probably good for preventing errors. But error handling is sometimes time consuming and you need to know exactly what error could happen. This type of thought is why I overlooked the great tags of cftry and cfcatch. It is extremely easy to use and only makes your code more bullet proof.
The logic behind cftry / cfcatch is simple:
<cftry>
Run some code
<cfcatch type=”any”>
<!-- type is used to tell what kind of error to look for. If you want to look for all errors, then use, “any”-->
What to do if the code generated an error
</cfcatch>
</cftry>
This concept seems simple, but the beauty of it is that if the code generates an error, the page will continue to load as if nothing is wrong. The user sees no blue error screen of death. Furthermore, if you catch the error you can run some other code that gives different output.
If you look at the cftry / cfcatch tags in terms of an IF clause, the code becomes very easy to use and understand.
<cfif> this code works
then use it.
<cfelse> that code didn’t work
then use this code.
</cfif>
Now let’s see some example code:
<cfif ISDEFINED(FORM.btnSubmit)>
<cfquery name=”getUserName” datasource=”DSNdatasource”>
SELECT UserName
FROM tlbCustomer
WHERE UserID = 1;
</cfquery>
</cfif>
<cfoutput> #getUserName.UserName# </cfoutput>
In this code, if the query fails, the user will get a database query error (i.e.) Blue Error Screen.
Now let’s see what a cftry / cfcatch can do for us:
<!--- Run the query to see if it will generate an error --->
<cfif ISDEFINED(FORM.btnSubmit)>
<cftry>
<cfquery name=”getUserName” datasource=”DSNdatasource”>
SELECT UserName
FROM tlbCustomer
WHERE UserID = 1;
</cfquery>
<cfset name=”myuser” value=”getUserName.UserName”>
<cfcatch type=”database”>
<!--- If the query is invalid, then set the variable to: UNKNOWN --->
<cfset name=”myuser” value=”UNKNOWN”>
</cfcatch>
</cftry>
</cfif>
<cfoutput> #myuser# </cfoutput>
If the query fails and generates an error, you will not see the ColdFusion Error page, but you will see the output of “UNKNOWN”.
Now that you have the knowledge of cftry / cfcatch, USE IT! It will save your users much frustration.
Aug14








