更好地处理 boost::program_options 中丢失/错误的密钥
当像下面这样的调用失败时,有没有办法知道涉及哪个键?
boost::program_options::variables_map vm;
...
int foo_bar = vm["some_key"].as<int>();
如果映射中缺少密钥,或者不能将其转换为 int,我会得到一个相当无信息的 bad_any_cast,并且我无法知道以下任何内容:
- 密钥涉及
- 存储的值,或者即使它存在。
- 涉及的类型
我找不到任何不涉及修改 boost 标头或将对上述内容的每个调用包装在 try..catch 块中的解决方案。 我认为这是一个常见问题,所以也许其他人知道更好的方法。
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 think it's a common issue, so maybe someone else knows a better approach.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Marco,
如果不修改库就无法获得更好的诊断。
但是,请注意,一般来说,我不确定这种情况下的例外情况是否应该非常详细:
- 如果您使用错误的类型来访问变量,则会出现编码错误。您可以使用调试器轻松跟踪它
- 如果访问不存在的变量,则需要 if vm.count,或使用默认值。同样,这可能是一个编码错误,最好使用调试器来解决。
我同意 bad_any_cast 是可以改进的,但似乎可以向用户报告的异常不应该是这里的目标,其中异常是编码错误的结果。
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.