3
votes

While I regularly use try/catch, I haven't needed for finally or rethrow. In my quest to broaden my knowledge and potentially improve the apps I work on, how would one use the additional options? I primarily work in Lucee and usually refer to the documentation at cfdocs but specifically for this question cfdocs.org/cftry and the examples don't go into the finally or rethrow... or even throw for that matter (but I'm familiar with throw).

Sample code might help me more than just documentation alone on this.

1
I did lookup the tag version but I guess I'm a little unclear of what it means by "cleanup"? Are they referring to "cleanup" like dropping temp tables that might have been created due to an action or perhaps deleting of CSV file that might have been used in a bulkload process... that kind of cleanup or are they referring to garbage collection? I'm probably overthinking this I'm sure... ¯\_(ツ)_/¯ - HPWD
Now THAT makes sense. If you'll take your comments here and put them in an answer, I'll mark it as correct. Thank you for the follow up. - HPWD
Also note that you don't need to "cleanup" a true temp table (if created like "#tempTable". The SQL server will automagically clean it up when the session ends (ie when the query completes and returns). - Shawn
@Shawn - I bumped up your comment. Good point. - HPWD

1 Answers

3
votes

A finally block is useful when you're managing resources, like a file handle. It can be used with or without a catch block. The example you'll usually see is closing a file handle:

var f = fileopen(filename, "r")
try {
    // Some dubious code
} finally {
    // f is freed, regardless of any exception thrown within the try block
    fileclose(f);
}

The finally block is called regardless of whether an exception is thrown within the try block or not.

rethrow is handy if you ultimately want to bubble the exception up the callstack, but first do something with it. I often find myself logging an exception before rethrowing it to generate a generic error page:

try {
    // Something sketchy
} catch (any e) {
    writelog(type="Error", file="uhoh.log", text=e.message);
    rethrow;
}

rethrow is also useful when you're dealing with weird ColdFusion exceptions that can only be identified by introspection, as opposed to catching them by type. Maybe you want to ignore a certain exception that is thrown whenever sketchy authentication code you didn't write (yeah, this is from experience) encounters an invalidated session, but bubble anything else up:

try {
    // Hey, external code, is this user authenticated?
} catch (any e) {
    if (e.id != MAGIC_NUMBER_TO_IGNORE)
        rethrow;
}

A good resource, as usual, is Ben Nadel's ColdFusion blog.