Hello everyone!
Looking at the MWE below:
It appears error/throw are run before get is finished, causing get to be interrupted and the default value to be returned, rather than the value which matches the valid key as expected.
Is this the intended behaviour for get in this circumstance?
I think it is rarely necessary to define an error() as the default value for get() - I stumbled upon this purely by accident this afternoon.
To my understanding there are (several) other ways to include this function that avoid this particular behaviour.
I wanted to post this here in-case anyone else comes across the same thing in the future and wonders (as I did) why passing a valid key to their Dict() did not returning the matching stored value, rather the error() set as the default value.
Thanks and have a nice day!
MWE
d = Dict("a" => 1, "b" =>2)
k = "a"
err_msg = "Key '$k' not present in dictionary: $d"
@assert haskey(d, k) err_msg
# While k = "a", the assertions hold, else 'err_msg' is returned
@assert get(d, k, 0) == 1 err_msg
@assert get(d, k, "Default value") == 1 err_msg
@assert get(d, k, ArgumentError("No matching key found")) == 1 err_msg
# While k = "a", the error including the string "Default value" is returned, before the assertion test is completed
@assert get(d, k, error("Default value")) == 1 err_msg
@assert get(d, k, throw(ArgumentError("Default value"))) == 1 err_msg
Related discussion (discovered automatically by discourse)
Output from versioninfo() (incase relevant)
julia> versioninfo()
Julia Version 1.12.6
Commit 15346901f00 (2026-04-09 19:20 UTC)
Build Info:
Official https://julialang.org release
Platform Info:
OS: macOS (arm64-apple-darwin24.0.0)
CPU: 8 Ć Apple M1
WORD_SIZE: 64
LLVM: libLLVM-18.1.7 (ORCJIT, apple-m1)
GC: Built with stock GC
Threads: 1 default, 1 interactive, 1 GC (on 4 virtual cores)
Environment:
JULIA_EDITOR = code
JULIA_VSCODE_REPL = 1