Search code examples
kdb

Using trap with KDB and non-declared variables?


Say for example I'm trying to do try-catch where x does not exist:

@[x;::;"error"]

I get an 'x error, rather than "error". What am I doing wrong?


Solution

  • Have a look at the documentation here https://code.kx.com/q/ref/apply/#trap "In the ternary, if evaluation of the function fails, the expression is evaluated"

    The function x cannot be evaluated as it does not exist. The function is not failing here it just cannot be called. The hint here is in evaluated - we can use value to check if the function exists.

    q)f:{x+x}
    q)@[value;`f;"error"]
    {x+x}
    q)@[value;`p;"error"]
    "error"
    

    The returns of values on the defined function f vs something that is not defined p >

    q)value f
    0x6161410003
    ,`x
    `symbol$()
    ,`
    5 3 4 2 2
    "..f"
    ""
    -1
    "{x+x}"
    q)value p
    'p
      [0]  value p
                 ^