Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 248
Marco Righele Avatar asked Oct 24 '22 15:10

Marco Righele


1 Answers

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.

like image 128
Vladimir Prus Avatar answered Oct 27 '22 11:10

Vladimir Prus