Monday, July 13, 2009

CF9 Beta: Finally, CFFinally

Though not a major feature, I am very pleased to see the cffinally tag in the ColdFusion 9 Beta. I have always missed the full try/catch/finally construct found in other languages.

While you could manually structure your code to simulate it, the absence of a finally clause makes it easier to overlook important cleanup tasks. For example, when working with lower level java objects it is easy to forget to close file objects or database connections. That can lead to problems with locked files or too many open connections. So I think the additional of finally will help promote better coding habits.

CFScript Example:

<h2>IText - HelloWorld Example with CFScript / Finally</h2>
outputFile = ExpandPath("./HelloWorld.pdf");
document = createObject("java", "com.lowagie.text.Document").init();
outStream = createObject("java", "").init(outputFile);

try {
writer = createObject("java", "com.lowagie.text.pdf.PdfWriter").getInstance(document, outStream);;
paragraph = createObject("java", "com.lowagie.text.Paragraph").init("Hello World");
// Deliberately cause an error
z = 10 / 0;
catch (java.lang.Exception e) {
WriteOutput("Entering Catch Clause! Message:"& e.message &"<br>");
finally {
WriteOutput("Entering Finally Clause!" &"<br>");
if (structKeyExists(VARIABLES, "document") && document.isOpen()) {
if (structKeyExists(VARIABLES, "outStream")) {

CFML Example:

<h2>IText - HelloWorld Example with CFFINALLY</h2>

<cfset outputFile = ExpandPath("./HelloWorld.pdf") />
<cfset document = createObject("java", "com.lowagie.text.Document").init() />
<cfset outStream = createObject("java", "").init(outputFile) />
<cfset writer = createObject("java", "com.lowagie.text.pdf.PdfWriter").getInstance(document, outStream) />
<cfset />
<cfset paragraph = createObject("java", "com.lowagie.text.Paragraph").init("Hello World") />
<cfset document.add(paragraph) />
<!--- Deliberately cause an error here --->
<cfset z = 10 / 0 />

<cfcatch type="any">
Entering Catch Clause! Message: <cfoutput>#cfcatch.message#</cfoutput><br/>

Entering Finally Clause!<br/>
<cfif structKeyExists(VARIABLES, "document") AND document.isOpen()>
<cfset document.close() />
<cfif structKeyExists(VARIABLES, "outStream")>
<cfset outStream.close() />


  © Blogger templates The Professional Template by 2008

Header image adapted from atomicjeep