What structured exception handling is

an article added by: Jose Carreto at 04092008


In: Root » Computers and technology » Programming » What structured exception handling is

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

Exception handling boils down to a single question: “What do you do if something occurs out of the ordinary?” If your database throws an error because you input bad data, exception handling determines how your system reacts. If CFHTTP throws an error because it can’t connect to a remote system, exception handling enables you to gracefully recover. No ColdFusion application is complete without at least some plan for how to handle exceptions. This article shows you the many things that you can do with exception handling, as well as how to pull these techniques together into a consolidated framework that enables your application to gracefully recover from almost any error. If an error occurs in your ColdFusion code, it normally stops page execution and outputs the standard ColdFusion error page, which shows what happened and where. Structured exception handling enables you to catch the error before the user sees it and do something different, depending on the circumstances of the error. Whenever something goes wrong in your application, it throws an error. You can choose to leave this error as is so that the user can see it, or you can catch the error and handle it yourself. You catch errors so that you can handle them as exceptions to the normal execution of a request. This is the essence of exception handling. The structured part of structured exception handling refers to the natural structure of ColdFusion’s exception framework. Notice that we depict the error-handling framework as a series of sieves, in which the top level of sieves (CFCATCH) catches expected errors, with any unexpected errors “falling through” to the next level, which is handled by a collection of CFERROR templates that handle specific errors. If an error falls through the CFERROR layer, or if no CFERROR is specified to handle the error, ColdFusion’s site-wide error handler catches the error. If you have no site-wide error handler, the error falls through to the user in its raw form. Structured exception handling is not always in effect. Suppose, for example, that an error occurs with the following code:

<cfquery name=”MyQuery”
   datasource=”#Request.MainDSN#”>
   ...
 </cfquery>

The error is not caught, because structured exception handling is not yet in effect, and the user sees the standard error message. Before you can catch the error, you must tell ColdFusion to try to catch an error:

<cftry>
   <cfquery name=”MyQuery”
   datasource=”#Request.MainDSN#”>
   ...
   </cfquery>
   <cfcatch type=”Any”>
   <!--- Handle the error --->
   </cfcatch>
   </cftry>

CFTRY tells ColdFusion to watch the enclosed block of code for errors, and CFCATCH tells ColdFusion what to do if an error occurs. CFCATCH type=”Any” tells ColdFusion that any error causes execution to pass to the code within that specific CFCATCH block. CFCATCH takes a single attribute named type, which specifies the type of error that is caught. If you want to catch only database errors, for example, you can use the following code:

<cftry>
   <cfquery name=”MyQuery”
   datasource=”#Request.MainDSN#”>
   ...
   </cfquery>
   <cfcatch type=”Database”>
   <!--- Only database errors cause this code to be run --->
   </cfcatch>
   </cftry>

If you use this CFTRY/CFCATCH construct, all database errors are caught and handled by the code within the CFCATCH tag pair, and all nondatabase errors fall through to the next level in your application’s structured exception-handling framework. By specifying an advanced exception type as the argument to CFCATCH’s type attribute, you can catch and handle very specific errors that occur outside the boundaries of ColdFusion Server. The point of having this many error types is that your structured exception handling can granularly respond to each type in a specific way. You could, for example, have an exception handler that catches two different types and handles them two different ways, as follows:

<cftry>
   ... Code to execute goes here ...
 <cfcatch type=”Database”>
 A database error occurred.
 </cfcatch>
 <cfcatch type=”Expression”>
 An expression error occurred
 </cfcatch>
 </cftry>

The preceding example catches either a Database error or an Expression error and outputs a different message depending on which one. If the error is not a Database or Expression error, the error is not caught and the user sees the standard message output. CFCATCH type=”Any” cannot catch one kind of error. Specifically, type=”Any” catches any error deriving from the Java class java.lang.Exception. type=”Any” does not, however, catch errors deriving from java.lang.Throwable. To catch these errors, you must define a special CFCATCH, as follows:

<cftry>
   ...
 <cfcatch type=”java.lang.Throwable”>
 ...
 </cfcatch>
 </cftry>

You rarely encounter this type because none of the standard ColdFusion features throw this type of error. You may be surprised to learn that that you can’t catch certain errors at all. The following code, for example, throws an error regardless of the CFTRY surrounding the bad code:

<cftry>
   <cfset>
   <cfcatch type=”Any”>
   An error occurred!
   </cfcatch>
   </cftry>

The CFSET has no content, so ColdFusion throws an error stating, Invalid CFML Construct Found on line 9 at column 7. This result may seem strange, however, because you have a CFTRY and CFCATCH type=”Any”. The problem here is that the bad CFSET created a compiletime error, which can’t be caught with CFCATCH. CFCATCH can catch only a run-time error, which occurs during the execution of the template. In the case of the preceding snippet, ColdFusion couldn’t successfully parse and compile the page, so the exception handling didn’t take effect. If you were to CFINCLUDE a page with a compile-time error, the calling page could catch a Template type error. This is rare, and you should be careful not to rely on exception handling to catch compile-time errors. The short answer is anything! You can handle an error any way that you see fit, from ignoring it completely to examining it in fine detail, to rerouting the user to an alternative template. You usually do one of two things, however. Either redirect the user to a different page or display a user-friendly message telling him what happened. You can follow either of two philosophies in redirecting the user. The first is to have a specific error page for each error that can occur and redirect the user to that specific page, as in the following example:

<cftry>
   ...
 <cfcatch type=”Database”>
 <cflocation url=”dberror.cfm”>
 </cfcatch>
 </cftry>

The downside to this approach is that you can’t tell exactly what happened and why. A better option is redirect the user to an error page, but pass the error message in the URL, as follows:

<cftry>
   ...
 <cfcatch type=”Database”>
 <cflocation
 url=”error.cfm?msg=#URLEncodedFormat(CFCATCH.Message)#”>
 </cfcatch>
 </cftry>

This code passes a detailed error message in a URL parameter to the error page. Another option is to directly display some type of message rather than redirecting the user, as follows:

<cftry>
   ...
 <cfcatch type=”Database”>
 A database error occurred.
 <cfabort>
 </cfcatch>
 </cftry>

You may notice that the preceding code adds a CFABORT after the message; you don’t want the errored page to continue execution after an error occurs. A final option that is rarely used is to ignore the error. This is usually appropriate only if you are expecting an error to occur, but it doesn’t matter to you whether the error occurs or not, as the following code shows:

<cftry>
   ...
 <cfcatch type=”Database”>
 <!--- Ignore this error --->
 </cfcatch>
 </cftry>

If you’re ignoring an error, adding a comment to the CFCATCH block is usually a good idea so that you’re not confused if you go back and read your code later. And be aware that ignoring an error can prove dangerous, because you may end up inadvertently catching a more serious error than the one you were expecting. At least logging the error by using CFLOG may be a good idea, even if you plan to ignore it, as in the following example:

<cftry>
   ...
 <cfcatch type=”Database”>
 <!--- Ignore this error, but log it in case there is a legitimate
 error --->
 <cflog log=”Application” text=”#CFCATCH.Message#”>
 </cfcatch>
 </cftry>

This way, you can review the specific error in the log file.

legal disclaimer

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

related articles

1. Building the company edit action template
The code in CompanyEditAction.cfm is like the code in CompanyAddAction.cfm, but the edit action updates rather than inserts. Create a file named CompanyEditAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”UpdateCompany” datasource=”#Request.MainDSN#”> UPDATE Company SET CompanyName = ‘#Trim(Form.CompanyName)#’, Address = ‘#Trim(Form.Address)#’, City = ‘#Trim(Form.City)...

2. Adding a New Employee to the Database
The CFQUERY in CompanyDeleteAction.cfm uses a DELETE statement with two SQL clauses: DELETE and WHERE. DELETE tells the database the table from which to delete a record, and WHERE tells the database which record to delete. You can watch the company delete process in action. Point your Web browser to http://<yourserver>/CFMXBible/Ch02/CompanyGetDeleteForm.cfm and enter a CompanyID. (To get a valid ID, go to the company list and pick a number from the ID column.) Click Submit to see the chosen company’s informatio...

3. Modifying an Employee in the Database
The DateFormat() function around the DateOfBirth column in the codereturns the employee’s birth date reformatted according to a display mask. DateOfBirth normally comes back from the database in the following format: 2002-01-01 00:00:00.0 That format is not very user-friendly. Calling DateFormat() with a mask of “mm/dd/yyyy” returns the date as follows: 01/01/2002 This version is, of course, more natural and easy to read. The same is true for the employee edit process...

4. Removing an Employee From the Database
The user must have the capability to remove employees from the database. The employee delete process is a simple combination of techniques that you have already learned, such as retrieving a record from the database, displaying that record in a template, and so on. The first page in this process is nearly identical to the employee get edit form. Create a file named EmployeeGetDeleteForm.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <html> <head> <ti...

5. Making direct links to the forms
Say that you want to modify or delete a company. Right now, you need to remember the company’s ID, go back to the launch pad, click Company Edit, and enter the company ID, all just to get to the edit form. Wouldn’t you rather click a company in the list and go directly to the edit form? ... <table> <tr> <td><b>ID</b></td> <td><b>Name</b></td> <td><b>Address</b></td> <td><b>City</b></t...

6. Using a Custom Tag
Custom tags are reusable, developer-authored extensions to the ColdFusion language. The custom tag that you create in the following parts displays today’s date in a familiar format. Create a file named TodaysDate.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfoutput>#DateFormat(Now(), “ddd, mmm d, yyyy”)#</cfoutput> Now() returns the current date and time, and DateFormat() reformats the date. To call your custom tag, open index.cfm, a...

7. Creating your physical data model
Physical data models are extracted from their logical counterparts by mapping logical objects to physical objects supported by the target database platform. The following table shows the relationship between logical and physical objects. In many cases, your physical data model almost mirrors your logical data model because entities typically map directly to the tables that store them. Exceptions to this rule are logical data models that contain nonspecific relationships and entity subtypes. Although entity subtypes are an advanced top...

8. Understanding All Relational Result Sets
This article can help you better understand complicated SQL containing multitable joins, group-related clauses, and aggregate functions—by far the most problematic topics for most database developers. You also learn the correct way to handle database exceptions and incorporate them as actual functionality in your ColdFusion application. You learn, too, how to increase performance by caching queries in memory for fast access. You can memorize SQL clauses and Bachus-Naur forms until you’re blue in the face, ...

9. How and when to use Group by Having and Distinct
After learning how SQL works internally, you can better learn how to put the more complicated aspects of it to use. First we need to clarify the difference between GROUP BY and DISTINCT. Quite a bit of confusion exists over these two clauses, because they often produce the same query results but for very different reasons. In fact, GROUP BY and DISTINCT are not related in any way whatsoever. The GROUP BY clause produces as its intermediate work product a table of rows representing each group, and a sort of “invisible third dimen...