Skip to main content
June 9, 2009
Question

Element col1 is undefined in CFML structure

  • June 9, 2009
  • 2 replies
  • 869 views

Sometimes i am getting "Element col1 is undefined in a CFML structure referenced as part of an expresssion".

How to trap this errror so that it does not throw any exception

    This topic has been closed for replies.

    2 replies

    Inspiring
    June 9, 2009

    In most cases, you do know what struct-keys to expect.  When you don't, you can usually get what you want by <cfloop>ing over the structure itself.  You can also, of course, obtain a list of the keys.

    To handle the case of bumping into a struct-key that doesn't exist, well, you've got two good choices ... depending on how probable you consider the event to be, and/or if the presence or absence of a key "means something."

    1. The key-exists function will tell you if "the bridge is out" so that you don't wander over a precipice.  The "tradeoff," theoretically at least, is that you are probing the structure for key-existence twice in a row.  Now, hash-lookups are extremely fast by their nature, and the CF/Java implementation is known to be "good."
    2. Exception-catching via <cftry> is another viable choice.  I happen to prefer to put such a block around everything, so that my app doesn't "lose face" if when something happens to go wrong, but exceptions do have a place in ordinary procedural logic.  You simply place a nice comfortable trampoline under the bridge, then charge right across it.  Most of the time the bridge holds-up just fine and you haven't wasted any time checking the floorboards.  When something "exceptional" does occur, however, you fall through the deck, land harmlessly on the trampoline and "respond appropriately."  If you find yourself in the exception-handler, you know that whatever you were looking for just happened.

    It all pretty-much coms down to your personal preference, because ColdFusion is typically not used to handle computationally-intensive nor time-consuming work.  Whatever makes your code cleanest and most-reliable is the path that you should take.

    Participating Frequently
    June 9, 2009

    1. Use StructKeyExists to check for the key before using it

    or

    2. Use cftry in combination with cfcatch around the code that

    generates the error.

    In 99% of the cases I've used StructKeyExists to check if the key

    exists (catching an error is more expensive and doesn't allow you to

    control the flow of the code in the same way as StructKeyExists).

    Mack

    June 9, 2009

    Thank you Mack.

    If i had known the name of the object i can use StructKeyExists , what about dynamically created objects.

    Participating Frequently
    June 9, 2009

    StructKeyExists works for dynamic objects also. The second parameter

    is the name of the key so it can be a hardcoded string, a variable, a

    string returned from a function, etc.

    Mack