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>
<cfscript>
outputFile = ExpandPath("./HelloWorld.pdf");
document = createObject("java", "com.lowagie.text.Document").init();
outStream = createObject("java", "java.io.FileOutputStream").init(outputFile);
try {
writer = createObject("java", "com.lowagie.text.pdf.PdfWriter").getInstance(document, outStream);
document.open();
paragraph = createObject("java", "com.lowagie.text.Paragraph").init("Hello World");
document.add(paragraph);
// 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()) {
document.close();
}
if (structKeyExists(VARIABLES, "outStream")) {
outStream.close();
}
}
</cfscript>
CFML Example:
<h2>IText - HelloWorld Example with CFFINALLY</h2>
<cftry>
<cfset outputFile = ExpandPath("./HelloWorld.pdf") />
<cfset document = createObject("java", "com.lowagie.text.Document").init() />
<cfset outStream = createObject("java", "java.io.FileOutputStream").init(outputFile) />
<cfset writer = createObject("java", "com.lowagie.text.pdf.PdfWriter").getInstance(document, outStream) />
<cfset document.open() />
<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/>
</cfcatch>
<cffinally>
Entering Finally Clause!<br/>
<cfif structKeyExists(VARIABLES, "document") AND document.isOpen()>
<cfset document.close() />
</cfif>
<cfif structKeyExists(VARIABLES, "outStream")>
<cfset outStream.close() />
</cfif>
</cffinally>
</cftry>
0 comments:
Post a Comment