- February 8, 2017
- Posted by: Bharat Patel
- Category: Uncategorized
ColdFusion 9 introduced cffinally tag. Cffinally or finally blocks are used within cftry or completion of try block. It is generally used for cleanup i.e. close database connections, close some objects or excecute code whether it is exception or not.
Category
Data output tag and error handling.
CFML Syntax
[code:cf]<cftry>
……
<cfcatch type="any">
……
</cfcatch>
<cffinally>
……
</cffinally>
</cftry>[/code]
CFScript Syntax
[code:cf]<cfscript>
try{
……
}catch(Any e){
……
}finally{
……
}
</cfscript>[/code]
Generally we use try and catch block to catch exception like application error, database error, custom error etc. But sometimes we need to run some code whether it is exception or not so generally we need to write both of it in catch block as well as after try block but now in ColdFusion 9 has introduced cffinally and many more useful tags. cffinally tag always use in try block. You can nest cftry/cfcatch/cffinally blocks. Cffinally tag executes code whether it is exception or not. You can also use finally in cfscript tag. These tags are meant for error handling. I hope it may be useful for you.
CFML Example
[code:cf]<cftry>
<cfset a = 10>
<cfset b = 0>
<cfset a = a / b>
<cfoutput><b>Ans : </b>#a#</cfoutput>
<cfcatch type="any">
<cfdump var="#cfcatch.Message#">
</cfcatch>
<cffinally>
<br /><b>Finally Block :</b>
<cfdump var="#a#">
</cffinally>
</cftry>[/code]
CFScript Example
[code:cf]
<cfscript>
a = 10;
b = 0;
try{
a = a / b;
writeOutput(‘<b>Ans : #a#</b>’);
}catch(Any e){
writeDump(e.message);
}finally{
writeOutput(‘<br /><b>Finally Block : </b>’);
writeDump(a);
}
</cfscript>
[/code]
Output
Division by zero.
Finally Block : 10