开发者

Better handling of missing/wrong key in boost::program_options

开发者 https://www.devze.com 2023-02-24 02:20 出处:网络
Is there a way to know which key was involved when a call like the following fails ? boost::program_options::variables_map vm;

Is there a way to know which key was involved when a call like the following fails ?

boost::program_options::variables_map vm;
...
int foo_bar = vm["some_key"].as<int>();

If the key is missing from the map, or is not convertible to int, I get a rather uninformative bad_any_cast, and I can't know any of the following:

  • the key involved
  • the stored value, or even if it's there.
  • the types involved

I can't find of any solution that doesn't involve either modifying the boost header or wrapping every call to the above in a try..catch block. I t开发者_开发技巧hink it's a common issue, so maybe someone else knows a better approach.


Marco,

there's no way to get better diagnostics without modifying the library.

However, please note that in general, I am not sure exceptions in this case are supposed to be very detailed: - If you use wrong type to access variable, you've got a coding error. You can easily track that down with a debugger - If you access a variable that does not exist, you either need to if vm.count, or use default value. Again, it's probably a coding error best solved using a debugger.

I agree that bad_any_cast is something that can be improved, but it does not seem that exception that can be reported to user should be a goal here, where exceptions are result of coding error.

0

精彩评论

暂无评论...
验证码 换一张
取 消