'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 1:[1]
You can use the value keyword to determine if a variable exists or not. Error trapping this might be what you're looking for?
q)@[value;`x;"error"]
"error"
q)x:12
q)@[value;`x;"error"]
12
Solution 2:[2]
Note that using value on the variable name will only work if the variable you're checking for is global, it would not work for a local variable:
q){@[value;`v;"error"]}[]
"error"
q){v:9;@[value;`v;"error"]}[]
"error"
Though in reality in most cases you would be looking for a global so this will work.
If it was a local you were looking for then things get a bit hacky and messy, but technically possible:
q){locals:?[(`$())!();();();{x!x}raze(value .z.s)1 2];$[`v in key locals;locals`v;'"error"]}[]
'error
q){v:9;locals:?[(`$())!();();();{x!x}raze(value .z.s)1 2];$[`v in key locals;locals`v;'"error"]}[]
9
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kylebonnes |
| Solution 2 | terrylynch |
