cftry/cfcatch

Contact Us or call 1-877-932-8228
cftry/cfcatch

cftry/cfcatch

So far, we have been looking at how to handle uncaught exceptions. It's much better if you can anticipate the exception, catch it, and respond. We do this with try/catch blocks. The syntax is shown below:

<cftry> <!---Code that might cause a problem---> <cfcatch type="Exception_Type"> <!---Error message---> </cfcatch> </cftry>

The major benefit of using try/catch blocks is that you can continue processing the page in the event that an error occurs. For example, you might have code that inserts a record into a database. Such code can fail if the database server is down (or for a number of other reasons). If the insert fails, you could catch the error and report it by email to the site administrator. However, the email code could also fail, so you might put that in a try/catch block as well. The code might look like this:

Code Sample:

Errors/Demos/TakeTwo.cfm
               <cftry>
	<cfquery datasource="dsn">
		--Insert record
	</cfquery>
	Record inserted.
	<cfcatch type="database">
		<cftry>
			<cfmail to="admin@webucator.com" from="errors@webucator.com" subject="Database error" type="html">
				Database error.  Record could not be inserted.
				<cfdump var="#cfcatch#">
			</cfmail>
			Sorry, we could not insert the record.  The site administrator has been informed.
			<cfcatch type="any">
				Sorry, we could not insert the record.  Please email the site administrator at admin@webucator.com.
			</cfcatch>
		</cftry>
	</cfcatch>
</cftry>
            

Exception Types

The table below shows the types of exceptions that can occur. These values can be used for the type attribute of the <cfcatch> tag.

Exception Types
Exception Type Description
Any All exceptions. Useful if you're not sure what type of exception could occur.
Application Custom exceptions thrown by <cfthrow> that either do not specify the type of exception or specify "Application" as the type.
Expression Invalid expressions, such as trying to concatenate with a plus sign (+).
Lock Occur when a cflock times out.
MissingInclude Errors where files specified by the <cfinclude>, <cfmodule>, and <cferror> tags cannot be found.
Object Errors that occur in code dealing with objects.
SearchEngine Errors that occur in code dealing with the Verity search engine.
Security Errors that occur in security code.
Template Errors that occur in ColdFusion syntax. These errors are usually caught at compile time.
Next