Reputation: 8127
I have the following functions.
foo(x) = x + 1
bar(x) = x * 2
I use them in a wrapper function (not sure whether this is even important).
function baz(x)
d = Dict{Symbol,Any}()
d[:foo] = foo(x)
d[:bar] = bar(x)
return d
end
The problem is that foo()
and bar()
can fail, and I want the code to continue running in this case. Introducing try catch
statements would make the code very messy, however. So, is there maybe one of the following two solutions out there, that could make this easier?
Dream Solution
A macro that I could just write in front of d[:foo] = foo(x)
and which in case of failure would write a default value do d[:foo]
.
Also-a Solution
A macro that would just continue if the code fails.
Upvotes: 2
Views: 324
Reputation: 8127
So, I managed to do the following. However, I have no clue if this is in any way good style.
macro tc(ex)
quote
try
$(esc(ex))
catch
missing
end
end
end
@tc foo(1)
1
@tc foo("a")
missing
Note the $(esc(ex))
. This is important. If the expression is not escaped, the macro will work as expected in the global scope but not inside a function (as in the question). If anyone can provide a crisp explanation of why this is the case, please add a comment.
Upvotes: 1