Throwing and catching Java exceptions

an article added by: Aris Buttler at 04092008



In: Categories » Computers and technology » Programming » Throwing and catching Java exceptions

Java objects throw exceptions in a slightly different way than ColdFusion does. Java exceptions are handled as follows:

<cfobject type=”JAVA” action=”Create” name=”myObject” class=”myClass”>
   <cftry>
   <cfset myVar = myObject.CauseException()>
   <cfcatch type=”Any”>
   <cfset exception = GetException(myObject)>
   <cfoutput>
   #exception.toString()#
   </cfoutput>
   </cfcatch>
   </cftry>
  

GetException() retrieves the most recent exception that occurred for myObject. Exception.toString() gets a message that you can display to the user. CFSCRIPT also contains a limited ability to perform exception handling. Instead of using CFTRY and CFCATCH, you would use the try and catch keywords in a CFSCRIPT block, as follows:

<cfscript>
   try {
   oExcel = CreateObject(“COM”, “Excel.Application”);
   }
   catch(Any exception) {
   WriteOutput(“An error occurred while instantiating a COM object.
   COM returned the following error message: #exception.Message#);
   }
 </cfscript>

If Excel is not installed on the ColdFusion Server that executes the preceding example, CreateObject() will throw an error that will then be caught by the catch block. Notice the difference between the CFCATCH syntax and the catch syntax. Inside CFSCRIPT, you specify the catch keyword, followed by the exception type, followed by the name of the exception object. The exception object is the equivalent of the CFCATCH structure you used earlier in this article. Unfortunately, CFSCRIPT’s exception handling is limited because there is no way to throw a custom error, and there is no way to rethrow an error once you’ve caught it. CFTRY and CFCATCH are useful for specific errors that occur in targeted part of code. You can, however, also catch any error that occurs in your application and pass control to a generalized error handler page by using the CFERROR tag. CFERROR is usually placed inside Application.cfm. A typical call looks as follows:

<cferror type=”EXCEPTION” template=”error.cfm” exception=”Any”>

That call to CFERROR tells ColdFusion that, if any uncaught exception of any type occurs in your application, it should redirect the user to error.cfm. This is similar to a CFCATCH type=”Any” that redirects the user to an error page, but CFERROR covers all code in your application rather than just a single targeted block. This approach has its advantages, because you can now give a user-friendly error page to the user regardless of where the error may have occurred. The disadvantage to using CFERROR by itself is that diagnosing the error is much more difficult, because you can’t pinpoint the location as easily. Your best course is to use CFTRY and CFERROR together—putting CFTRY in specific areas of your code and then relying on CFERROR for unexpected errors that cannot be handled as exceptions. Whenever CFERROR encounters an error, it passes page execution to the template specified in the Template attribute. The error page has access to information about the error as well as all the content generated up to the point that the error occurred. A good idea is to use the error template to e-mail the site administrator, sending him all the error information, and then to output a user-friendly error message that integrates with the regular graphical treatment for your site. The code shows a well-written error page.

<!--- Email the site administrator --->
   <cfmail to=”admin@site.com”
   from=”site@site.com”
   subject=”An error occurred”>
   An error occurred while processing the template
   #Error.TagContext[1].Template# at line #Error.TagContext[1].Line#. The
   diagnostic information is below:
   Error Type:
   #Error.RootCause.Type#
   Referer:
   #Error.HTTPReferer#
   Error Message:
   #Error.RootCause.Message#
   Error Detail:
   #Error.Rootcause.Detail#
   </cfmail>
   <!--- Tell the user an error occurred. If this site had a graphical
   treatment, we would also include the code for that here. --->
 An error occurred during your request. Please try again.

The CFERROR example that we show you at the beginning of this part has an exception attribute. CFERROR’s exception attribute is similar to CFCATCH’s type attribute: It tells ColdFusion which type of exception affects the CFERROR tag. Suppose, for example, that you have the following calls to CFERROR:

<cferror type=”EXCEPTION” template=”dberr.cfm” exception=”Database”>
   <cferror type=”EXCEPTION” template=”anyerr.cfm” exception=”Any”>

Any time an uncaught database error occurs, ColdFusion redirects the user to dberr.cfm. Any other type of uncaught error redirects the user to anyerr.cfm. The reason that you want to have specific error templates for specific exception types is that each one exposes different information. Until Version 4.01 of ColdFusion Server, you had only two types of CFERROR: Request and Validate. The error templates associated with those CFERROR types could not include any ColdFusion code, because any error occurring in the error template would throw the server into an infinite loop. ColdFusion 4.5 introduced two new types, Exception and Monitor. Monitor was a great idea; it enabled you to run code for any error that occurred, regardless of whether it was caught. The only problem is that it would occasionally cause errors worse than what was originally thrown, and it has now been deprecated in ColdFusion MX. That leaves you with the final type, Exception, which is the only one that you should use from now on. Unlike CFERROR’s Request and Validate types, the Exception type can use CFML in the errorhandling template. Suppose that your error isn’t caught by CFTRY and CFCATCH. CFERROR doesn’t catch it either. What’s your last resort before the user sees a scary, raw error message? The site-wide error handler. The site-wide error handler template works like a CFERROR for the entire server, with some differences. The site-wide error handler can use ColdFusion tags just as the CFERROR template (with type=”EXCEPTION”) can. It doesn’t, however, have access to any of the error variables. (This is in conflict with the documentation, but tests have confirmed that you can’t use the Error scope in the site-wide error handler.) As such, you can e-mail the Administrator to tell him that an error occurred, but you can’t tell him which error occurred. The site-wide error handler should be a last resort; ideally it would never be called in the lifetime of an application, because CFERROR should catch any unexpected errors. This means that your site-wide handler should create a log entry and e-mail the administrator every time that the site-wide handler is called, because a call to the site-wide handler could indicate a serious problem with your application or with ColdFusion Server in general.

ColdFusion logs all the errors that occur in your application. You can get a history of all the errors in your application by viewing the log files and seeing what happened when. The log files are stored inside the cf_root\logs\ directory. The log file that you should be most concerned with is Application.log, which contains the errors that occur in your application. You can track an error by looking at the log files and finding the record. Even errors that are caught with CFCATCH or CFERROR are stored in Application.log, so you can see exactly what happened even if CFCATCH obscures the error. You can also write your own messages to the log files by using CFLOG as follows:

<cflog text=”My Message” file=”MyLog”>

That writes a message to a file called MyLog.log inside the cf_root\logs\ directory. This can be very useful for certain problematic situations in which you want to log a specific error. Do not log every error that occurs because doing so unnecessarily burdens the server. ColdFusion offers a wide range of exception handling techniques, from CFTRY and CFCATCH to the all-encompassing site-wide error handler. Each technique can be powerful by itself, but only when these three are intelligently integrated do you reach the full potential of ColdFusion’s exception handling framework. In this article you learn about the different ways to use ColdFusion’s exception-handling framework and how the different pieces work together. You also learn about the many types of errors that can be thrown and caught with CFCATCH and CFERROR, and you even learn how to create your own custom error types that you can use for your own purposes.

legal notice

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.

Useful tools and features

Throwing and catching Java exceptions  
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. ColdFusion Can Be Extended In Many Ways
In addition to being one of the easiest Web-programming languages, ColdFusion is also one of the most easily extensible languages, because it can interface with many different technologies, as shown in the following list: Java objects, which are standalone packages of code written in the Java language Custom tags written in C++ or Java, which are pieces of code to be used only with ColdFusion, but which are written in either C++ or Java Java Server Page (JSP) tag libraries, which are originally built for use w...

2. First ColdFusion Application
You learn by doing, and then we go back and explain how ColdFusion worked its magic. Before you get started, though, you must learn a few terms, set up the database, and create the Web directory that you’re going to use. These are some terms that you should know: A template is a file with a .cfm extension. ColdFusion executes these templates and produces HTML that is returned to the user’s browser. A page is what appears in your browser. It is rendered from the HTML that ColdFusion Server sends back ...

3. Building the company add action template
In this article, you create the template that puts your form data into the database. Create a file named CompanyAddAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”InsertCompany” datasource=”#Request.MainDSN#”> INSERT INTO Company( CompanyName, Address, City, State, ZipCode, Comments ) VALUES ( ‘#Trim(Form.CompanyName)#’, ‘#Trim(Form.Address)#’, ...

4. Modifying a Company in the Database
The data that CFQUERY requests from the database comes back in a result set, and the Name attribute tells ColdFusion what that result set is to be named. The SQL statement consists of three clauses: SELECT, FROM, and ORDER BY. SELECT tells the database which columns to retrieve from the database; FROM tells the database which table to retrieve those columns from; and ORDER BY tells the database how to sort the results. The result set returned from CFQUERY contains multiple rows of data, and each row has multiple columns. It would ...

5. 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)...

6. 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...

7. 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...

8. 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...