Author: Steven Neiland

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

Back when ColdFusion 9 was releashed the cftry/cfcatch tags were enhanced to include a new tag <cffinally>. While I have been aware of it, up to now I have not used it simply because I did not understand why or where it would be useful.

What <cffinally> does (According to Adobe)

If you read about the tag in the adobe live docs: <cffinally> you get this explanation:

Used inside a cftry tag. Code in the cffinally block is processed after the main cftry code and, if an exception occurs, the cfcatch code. The cffinally block code always executes, whether or not there is an exception.

Big deal so code inside the cffinally block runs in the end regardless of if there is an error that throws the catch, why is this useful? According to this explanation the following two code blocks behave identically:

Using <cffinally>

.... ....

Not using <cffinally>

.... ....

These two blocks of code do in fact behave identically in this scenario and because of Adobe's less than stellar documentation I never knew about <cffinally>'s hidden power.

What <cffinally> actually does

So I was reading up on another language when I came across that language's documentation for its version of try/catch/finally.

In the documentation it stated that:

Code inside a "finally" block gets executed after the code in the try/catch block regardless of if there was an error thrown to execute the catch block and regardless of if an error occurs in the catch block.

Ding, ding, ding, ding, light bulb moment. So of course the moment I read that I had to go see if this also holds true for ColdFusion and guess what, it does! When you run this code you will get the below output:

Error thrown: Do something clever to try fix it
Finally block executed regardless of any errors in the try or catch block
Error thrown: Do something clever to try fix it
Finally block executed regardless of any errors in the try or catch block
{An error message that "Variable BIRD is undefined."}

So there you have it, you should use <cffinally> whenever you must run some post processing after a block of code is executed which can throw an error and where the error handling code inside your catch may also throw an error.

What Do You Think?

Reader Comments

Ben Nadel's Gravatar
Ben Nadel
Tuesday, May 6, 2014 at 8:03:55 AM EDT

I was actually just looking into this stuff this morning. I love the Finally tag; but, had a doubt about what would happen if the catch tag threw an error. This is so comforring.

Commenting has been disabled.

Archives Blog Listing

Tag Listing

Learn CF In A Week


Fork me on GitHub