5

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.

Marco Righele
  • 2,702
  • 3
  • 23
  • 23
  • 3
    I believe the samples provided in the documentation generally check every option using `if(vm.count("some_key") != 0)`, so it seems this is how they intended it to be used. – Björn Pollex Apr 13 '11 at 12:41
  • Having to check every single key is less than ideal though, I was hoping in a less verbose solution.I noticed that in recent versions of boost one can set an option as "required", thus raising an exception if the key is missing. Of course this won't work for optional values, and I still have the problem of handling invalid values – Marco Righele Apr 14 '11 at 09:57

1 Answers1

3

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.

Vladimir Prus
  • 4,600
  • 22
  • 31
  • Thanks for you answer. Actually I was under the impression that having the user using a wrong value for an option would throw the bad_any_cast exception, but it is not the case. So yes, in that regard it must be a coding error. Still, I think a missing value could be handled better. – Marco Righele Apr 14 '11 at 13:31