You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I want to print a helpful message when a required keyword is missing from a json file. I mimicked the example code given here to print a message about a caught exception. Instead of printing “key 'foo' not found” it continued to print the less helpful “type must be number, but is null”. I eventually realized that the difference was not related to handling the exception—the default handler was fine—but it came down to how I wrote the keyword lookup. This produces “type must be number, but is null”:
float foo = properties["foo"];
While this produces what I wanted, “key ‘foo’ not found”:
float foo = properties.at("foo");
Is this an intentional/expected difference between [] and at()? And is the solution to my desire for more specific “keyword not found” error messages simply to use at() instead of []? Or is something more subtle going on?
(I’m using version 3.6.1)
The text was updated successfully, but these errors were encountered:
Yes, properties["foo"] creates a new null entry if the entry isn't found and properties is not const. If it is const, then it asserts (I think). If you aren't sure if it's there, you need to use find() first to check, or at() with exception handling.
Thanks @gregmarr for the explanation. Performance of json reading is not a key issue in my application, it only happens at initialization. So I will replace [] with at() on nlohmann::json objects in order to get better error messages “for free.”
I want to print a helpful message when a required keyword is missing from a json file. I mimicked the example code given here to print a message about a caught exception. Instead of printing “key 'foo' not found” it continued to print the less helpful “type must be number, but is null”. I eventually realized that the difference was not related to handling the exception—the default handler was fine—but it came down to how I wrote the keyword lookup. This produces “type must be number, but is null”:
While this produces what I wanted, “key ‘foo’ not found”:
Is this an intentional/expected difference between
[]
andat()
? And is the solution to my desire for more specific “keyword not found” error messages simply to useat()
instead of[]
? Or is something more subtle going on?(I’m using version 3.6.1)
The text was updated successfully, but these errors were encountered: