Whatever message this page gives is out now! Go check it out!
<cfcatch type = "exception type">
Exception processing code here </cfcatch>Attribute | Req/Opt | Default | Description |
name | Optional | Variable name for cfcatch expression. | |
type | Optional | Any |
|
#cfcatch.type# |
<cfthrow type = "MyApp.BusinessRuleException.InvalidAccount"><cfcatch type = "MyApp.BusinessRuleException.InvalidAccount"><cfcatch type = "MyApp.BusinessRuleException"><cfcatch type = "MyApp">cfcatch variable | Content |
cfcatch.type | Type: Exception type, as specified in cfcatch. |
cfcatch.message | Message: Exception's diagnostic message, if provided; otherwise, an empty string; in the cfcatch.message variable. |
cfcatch.detail | Detailed message from the CFML interpreter or specified in a cfthrow tag. When the exception is generated by ColdFusion (and not cfthrow), the message can contain HTML formatting and can help determine which tag threw the exception. |
cfcatch.tagcontext | An array of tag context structures, each representing one level of the active tag context at the time of the exception. |
cfcatch.NativeErrorCode | Applies to type = "database". Native error code associated with exception. Database drivers typically provide error codes to diagnose failing database operations. Default value is -1. |
cfcatch.SQLState | Applies to type = "database". SQLState associated with exception. Database drivers typically provide error codes to help diagnose failing database operations. Default value is 1. |
cfcatch.Sql | Applies to type = "database". The SQL statement sent to the data source. |
cfcatch.queryError | Applies to type ="database". The error message as reported by the database driver. |
cfcatch.where | Applies to type= "database". If the query uses the cfqueryparam tag, query parameter name-value pairs. |
cfcatch.ErrNumber | Applies to type = "expression". Internal expression error number. |
cfcatch.MissingFileName | Applies to type = "missingInclude". Name of file that could not be included. |
cfcatch.LockName | Applies to type = "lock". Name of affected lock (if the lock is unnamed, the value is "anonymous"). |
cfcatch.LockOperation | Applies to type = "lock". Operation that failed (Timeout, Create Mutex, or Unknown). |
cfcatch.ErrorCode | Applies to type = "custom". String error code. |
cfcatch.ExtendedInfo | Applies to type = "application" and "custom". Custom error message; information that the default exception handler does not display. |
ColdFusion advanced exception type |
COM.Allaire.ColdFusion.CFEXECUTE.OutputError |
COM.Allaire.ColdFusion.CFEXECUTE.Timeout |
COM.Allaire.ColdFusion.FileException |
COM.Allaire.ColdFusion.HTTPAccepted |
COM.Allaire.ColdFusion.HTTPAuthFailure |
COM.Allaire.ColdFusion.HTTPBadGateway |
COM.Allaire.ColdFusion.HTTPBadRequest |
COM.Allaire.ColdFusion.HTTPCFHTTPRequestEntityTooLarge |
COM.Allaire.ColdFusion.HTTPCGIValueNotPassed |
COM.Allaire.ColdFusion.HTTPConflict |
COM.Allaire.ColdFusion.HTTPContentLengthRequired |
COM.Allaire.ColdFusion.HTTPContinue |
COM.Allaire.ColdFusion.HTTPCookieValueNotPassed |
COM.Allaire.ColdFusion.HTTPCreated |
COM.Allaire.ColdFusion.HTTPFailure |
COM.Allaire.ColdFusion.HTTPFileInvalidPath |
COM.Allaire.ColdFusion.HTTPFileNotFound |
COM.Allaire.ColdFusion.HTTPFileNotPassed |
COM.Allaire.ColdFusion.HTTPFileNotRenderable |
COM.Allaire.ColdFusion.HTTPForbidden |
COM.Allaire.ColdFusion.HTTPGatewayTimeout |
COM.Allaire.ColdFusion.HTTPGone |
COM.Allaire.ColdFusion.HTTPMethodNotAllowed |
COM.Allaire.ColdFusion.HTTPMovedPermanently |
COM.Allaire.ColdFusion.HTTPMovedTemporarily |
COM.Allaire.ColdFusion.HTTPMultipleChoices |
COM.Allaire.ColdFusion.HTTPNoContent |
COM.Allaire.ColdFusion.HTTPNonAuthoritativeInfo |
COM.Allaire.ColdFusion.HTTPNotAcceptable |
COM.Allaire.ColdFusion.HTTPNotFound |
COM.Allaire.ColdFusion.HTTPNotImplemented |
COM.Allaire.ColdFusion.HTTPNotModified |
COM.Allaire.ColdFusion.HTTPPartialContent |
COM.Allaire.ColdFusion.HTTPPaymentRequired |
COM.Allaire.ColdFusion.HTTPPreconditionFailed |
COM.Allaire.ColdFusion.HTTPProxyAuthenticationRequired |
COM.Allaire.ColdFusion.HTTPRequestURITooLarge |
COM.Allaire.ColdFusion.HTTPResetContent |
COM.Allaire.ColdFusion.HTTPSeeOther |
COM.Allaire.ColdFusion.HTTPServerError |
COM.Allaire.ColdFusion.HTTPServiceUnavailable |
COM.Allaire.ColdFusion.HTTPSwitchingProtocols |
COM.Allaire.ColdFusion.HTTPUnsupportedMediaType |
COM.Allaire.ColdFusion.HTTPUrlValueNotPassed |
COM.Allaire.ColdFusion.HTTPUseProxy |
COM.Allaire.ColdFusion.HTTPVersionNotSupported |
COM.Allaire.ColdFusion.POPAuthFailure |
COM.Allaire.ColdFusion.POPConnectionFailure |
COM.Allaire.ColdFusion.POPDeleteError |
COM.Allaire.ColdFusion.Request.Timeout |
COM.Allaire.ColdFusion.SERVLETJRunError |
COM.Allaire.ColdFusion.HTTPConnectionTimeout |
<!--- The cfcatch example that uses TagContext to display the tag stack. --->
<h3>cftry Example</h3>
<!--- Open a cftry block. --->
<cftry>
<!--- Notice misspelled tablename "employees" as "employeeas". --->
<cfquery name = "TestQuery" dataSource = "cfdocexamples">
SELECT *
FROM employees
</cfquery>
<!--- Other processing goes here. --->
<!--- Specify the type of error for which we search. --->
<cfcatch type = "Database">
<!--- The message to display. --->
<h3>You've Thrown a Database <b>Error</b></h3>
<cfoutput>
<!--- The diagnostic message from ColdFusion. --->
<p>#cfcatch.message#</p>
<p>Caught an exception, type = #CFCATCH.TYPE#</p>
<p>The contents of the tag stack are:</p>
<cfdump var="#cfcatch.tagcontext#">
</cfoutput>
</cfcatch>
</cftry><!---
Use Case 1: Data Access Error Handling
Demonstrates catching and handling data access errors gracefully
--->
<h1>Data Access Error Handling Demo</h1>
<p><strong>What This Demo Shows:</strong> How to handle data access errors gracefully using cftry/cfcatch.</p>
<hr>
<h2>Example 1: Array Access Error</h2>
<cftry>
<cfset users = ["John", "Jane", "Bob"]>
<cfset userIndex = 10>
<cfif userIndex GT arrayLen(users)>
<cfthrow type="ArrayIndexOutOfBounds"
message="User not found"
detail="Requested index #userIndex# but only #arrayLen(users)# users exist">
</cfif>
<p>✓ User found: <cfoutput>#users[userIndex]#</cfoutput></p>
<cfcatch type="ArrayIndexOutOfBounds">
<p><strong>✗ Array Index Error</strong></p>
<cfoutput>
<p>Error Type: #cfcatch.type#</p>
<p>Message: #cfcatch.message#</p>
<p>Detail: #cfcatch.detail#</p>
</cfoutput>
<p>Fallback: Showing first user instead...</p>
<cflog file="array_errors" type="error" text="Array access failed: #cfcatch.message#">
</cfcatch>
</cftry>
<hr>
<h2>Example 2: Struct Key Not Found</h2>
<cftry>
<cfset userRecord = {
id: 1,
name: "John Doe",
email: "john@example.com"
}>
<cfif NOT structKeyExists(userRecord, "phoneNumber")>
<cfthrow type="MissingData"
message="Required field missing"
detail="phoneNumber is required but not found in record">
</cfif>
<p>✓ Phone Number: <cfoutput>#userRecord.phoneNumber#</cfoutput></p>
<cfcatch type="MissingData">
<p><strong>✗ Missing Data Error</strong></p>
<cfoutput>
<p>Message: #cfcatch.message#</p>
<p>Detail: #cfcatch.detail#</p>
</cfoutput>
<p>Solution: Add required field or use default value</p>
<cflog file="data_errors" type="error" text="Missing data: #cfcatch.message#">
</cfcatch>
</cftry>
<hr>
<h2>Example 3: Successful Data Access</h2>
<cftry>
<cfset employees = [
{id: 1, name: "Alice Johnson", department: "Engineering", salary: 85000},
{id: 2, name: "Bob Williams", department: "Marketing", salary: 65000},
{id: 3, name: "Carol Davis", department: "Sales", salary: 70000}
]>
<cfset engineeringEmployees = []>
<cfloop array="#employees#" index="emp">
<cfif emp.department EQ "Engineering">
<cfset arrayAppend(engineeringEmployees, emp)>
</cfif>
</cfloop>
<p><strong>✓ Data Retrieved Successfully</strong></p>
<p>Found <cfoutput>#arrayLen(engineeringEmployees)#</cfoutput> employee(s) in Engineering</p>
<cfloop array="#engineeringEmployees#" index="emp">
<cfoutput>
<p>#emp.id#. #emp.name# - #emp.department# - $#numberFormat(emp.salary, "0,000")#</p>
</cfoutput>
</cfloop>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr><!--- Example 1: File Type Validation --->
<h2>Example 1: File Type Validation</h2>
<cftry>
<cfset testFileName = "document.exe">
<cfset allowedTypes = "jpg,jpeg,png,pdf,doc,docx">
<cfset fileExtension = listLast(testFileName, ".")>
<cfif NOT listFindNoCase(allowedTypes, fileExtension)>
<cfthrow type="InvalidFileType"
message="File type not allowed"
detail="Only #allowedTypes# files are accepted. You tried: .#fileExtension#">
</cfif>
<p>✓ File type is valid</p>
<cfcatch type="InvalidFileType">
<p><strong>✗ Invalid File Type</strong></p>
<cfoutput>
<p>Message: #cfcatch.message#</p>
<p>Detail: #cfcatch.detail#</p>
</cfoutput>
<cflog file="file_errors" type="warning" text="Invalid file type: #testFileName#">
</cfcatch>
</cftry>
<hr>
<!--- Example 2: File Size Limit --->
<h2>Example 2: File Size Limit</h2>
<cftry>
<cfset uploadedFileSize = 15728640> <!--- 15 MB --->
<cfset maxFileSize = 10485760> <!--- 10 MB --->
<cfif uploadedFileSize GT maxFileSize>
<cfthrow type="FileSizeExceeded"
message="File size exceeds limit"
detail="Max: #maxFileSize / 1048576# MB. Your file: #uploadedFileSize / 1048576# MB">
</cfif>
<p>✓ File size is within limits</p>
<cfcatch type="FileSizeExceeded">
<p><strong>✗ File Too Large</strong></p>
<cfoutput>
<p>Message: #cfcatch.message#</p>
<p>Detail: #cfcatch.detail#</p>
</cfoutput>
<p>Please reduce file size and try again.</p>
</cfcatch>
</cftry>
<hr>
<!--- Example 3: Safe File Upload --->
<h2>Example 3: Safe File Upload</h2>
<cftry>
<cfset mockUpload = {
serverFile: "document_123.pdf",
fileSize: 524288,
contentType: "application/pdf",
serverDirectory: expandPath("./uploads/")
}>
<p><strong>✓ File Upload Successful</strong></p>
<cfoutput>
<p>File Name: #mockUpload.serverFile#</p>
<p>File Size: #numberFormat(mockUpload.fileSize / 1024, "0.00")# KB</p>
<p>File Type: #mockUpload.contentType#</p>
</cfoutput>
<cflog file="file_uploads" type="information" text="File uploaded: #mockUpload.serverFile#">
<cfcatch type="any">
<p><strong>✗ Upload Error</strong></p>
<cfoutput>
<p>Message: #cfcatch.message#</p>
</cfoutput>
<cflog file="upload_errors" type="error" text="Upload failed: #cfcatch.message#">
</cfcatch>
</cftry>
<hr><!--- Example 1: Invalid JSON Response --->
<h2>Example 1: Invalid JSON Response</h2>
<cftry>
<cfset invalidJSON = "{name: 'John', invalid json}">
<cfset parsedData = deserializeJSON(invalidJSON)>
<p>✓ JSON Parsed Successfully</p>
<cfcatch type="any">
<p><strong>✗ JSON Parse Error</strong></p>
<cfoutput>
<p>Message: #cfcatch.message#</p>
</cfoutput>
<p>The API returned invalid JSON. Using cached data instead.</p>
<cflog file="api_errors" type="error" text="JSON parse error: #cfcatch.message#">
</cfcatch>
</cftry>
<hr>
<!--- Example 2: API with Retry Logic --->
<h2>Example 2: Retry Logic for Failed Requests</h2>
<cfset maxRetries = 3>
<cfset retryCount = 0>
<cfset success = false>
<cfloop condition="retryCount LT maxRetries AND NOT success">
<cftry>
<cfset retryCount = retryCount + 1>
<!--- Simulate: Fails first 2 attempts, succeeds on 3rd --->
<cfif retryCount LT 3>
<cfthrow type="APIError" message="Temporary API failure (attempt ##retryCount)">
<cfelse>
<cfset success = true>
</cfif>
<cfcatch type="any">
<cfif retryCount LT maxRetries>
<cfoutput>
<p>⚠️ Attempt ##retryCount## failed: #cfcatch.message#</p>
<p>Retrying in #retryCount# second(s)...</p>
</cfoutput>
<cfset sleep(retryCount * 1000)>
<cfelse>
<cfoutput>
<p><strong>✗ All attempts failed</strong></p>
<p>Failed after #maxRetries# attempts: #cfcatch.message#</p>
</cfoutput>
</cfif>
<cflog file="api_retries" type="warning" text="Retry ##retryCount## failed: #cfcatch.message#">
</cfcatch>
</cftry>
</cfloop>
<cfif success>
<p><strong>✓ API Request Succeeded After <cfoutput>#retryCount#</cfoutput> Attempt(s)</strong></p>
</cfif>
<hr>
<!--- Example 3: Successful API Call --->
<h2>Example 3: Successful API Call</h2>
<cftry>
<cfset mockAPIResponse = {
success: true,
data: [
{id: 1, name: "Product A", price: 29.99},
{id: 2, name: "Product B", price: 39.99}
]
}>
<cfset products = mockAPIResponse.data>
<p><strong>✓ API Request Successful</strong></p>
<p>Retrieved <cfoutput>#arrayLen(products)#</cfoutput> products</p>
<cfloop array="#products#" index="product">
<cfoutput>
<p>#product.id#. #product.name# - $#numberFormat(product.price, "0.00")#</p>
</cfoutput>
</cfloop>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr><h1>Math & Division Error Handling Demo</h1>
<p><strong>What This Demo Shows:</strong> Preventing division by zero and handling math errors.</p>
<hr>
<!--- Example 1: Division by Zero --->
<h2>Example 1: Division by Zero Prevention</h2>
<cftry>
<cfset numerator = 100>
<cfset denominator = 0>
<cfif denominator EQ 0>
<cfthrow type="DivisionByZero"
message="Cannot divide by zero"
detail="Division of #numerator# by 0 is undefined">
</cfif>
<cfset result = numerator / denominator>
<cfoutput><p>✓ Result: #result#</p></cfoutput>
<cfcatch type="DivisionByZero">
<p><strong>✗ Division by Zero Error</strong></p>
<cfoutput>
<p>Message: #cfcatch.message#</p>
<p>Detail: #cfcatch.detail#</p>
</cfoutput>
<p>Returning default value: 0</p>
<cfset result = 0>
</cfcatch>
</cftry>
<hr>
<!--- Example 2: Safe Division Function --->
<h2>Example 2: Safe Division Function</h2>
<cfscript>
function safeDivide(num1, num2) {
try {
if (num2 == 0) {
throw(type="DivisionByZero", message="Cannot divide by zero");
}
return num1 / num2;
} catch (any e) {
writeLog(file="math_errors", type="error", text=e.message);
return 0; // Return default value
}
}
</cfscript>
<cfset result1 = safeDivide(100, 5)>
<cfset result2 = safeDivide(100, 0)>
<p><strong>Safe Division Results:</strong></p>
<cfoutput>
<p>100 ÷ 5 = #result1#</p>
<p>100 ÷ 0 = #result2# (default value, no crash)</p>
</cfoutput>
<hr>
<!--- Example 3: Percentage Calculation --->
<h2>Example 3: Percentage Calculation with Validation</h2>
<cftry>
<cfset totalSales = 50000>
<cfset targetSales = 100000>
<cfif targetSales EQ 0>
<cfthrow type="InvalidTarget" message="Target cannot be zero">
</cfif>
<cfset percentAchieved = (totalSales / targetSales) * 100>
<p><strong>✓ Sales Performance</strong></p>
<cfoutput>
<p>Total Sales: $#numberFormat(totalSales, "0,000")#</p>
<p>Target: $#numberFormat(targetSales, "0,000")#</p>
<p>Achievement: #numberFormat(percentAchieved, "0.00")#%</p>
</cfoutput>
<cfcatch type="any">
<p><strong>✗ Calculation Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
<!--- Example 4: Discount Calculation --->
<h2>Example 4: Discount Calculation</h2>
<cftry>
<cfset originalPrice = 99.99>
<cfset discountPercent = 20>
<cfif discountPercent LT 0 OR discountPercent GT 100>
<cfthrow type="InvalidDiscount"
message="Discount must be 0-100%"
detail="You entered: #discountPercent#%">
</cfif>
<cfset discountAmount = (originalPrice * discountPercent) / 100>
<cfset finalPrice = originalPrice - discountAmount>
<p><strong>✓ Discount Applied</strong></p>
<cfoutput>
<p>Original: $#numberFormat(originalPrice, "0.00")#</p>
<p>Discount: #discountPercent#% (-$#numberFormat(discountAmount, "0.00")#)</p>
<p>Final: $#numberFormat(finalPrice, "0.00")#</p>
</cfoutput>
<cfcatch type="InvalidDiscount">
<p><strong>✗ Invalid Discount</strong></p>
<cfoutput>
<p>Message: #cfcatch.message#</p>
<p>Detail: #cfcatch.detail#</p>
</cfoutput>
</cfcatch>
</cftry>
<hr>