愚蠢的问题(但我在 boost.org 上没有找到任何内容):如何从 boost::program_options 捕获异常?调用
#include <boost/program_options.hpp>
#include <iostream>
int main(int argc, char** argv){
bool opt;
namespace bpo = boost::program_options;
bpo::options_description options("Allowed options");
options.add_options()
("opt", bpo::bool_switch(&opt));
bpo::variables_map options_vm;
try {
bpo::store(bpo::parse_command_line(argc, argv, options), options_vm);
bpo::notify(options_vm);
}
catch(const std::exception &e){
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
任何选项,但
--opt
产量
libc++abi: terminating due to uncaught exception of type boost::wrapexcept<boost::program_options::unknown_option>: unrecognised option '--optnsdf'
为什么
catch(const std::exception &e)
没有捕获异常?我如何正确捕获 catch(const boost::wrap exceptboost::program_options::unknown_option& e)is not intended, also because there can be other program options-related exceptions, such as
boost::wrapexceptboost::program_options::invalid_command_line_syntax`,以及其他可能。
网上是否有任何用于 boost 程序选项例外的类层次结构?
可以通过引用捕获异常基类
program_options::error
:
#include <array>
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main() {
std::array argv{"demo", "--oops", static_cast<char const*>(nullptr)};
po::options_description options("Allowed options");
bool opt;
options.add_options()("opt", po::bool_switch(&opt));
po::variables_map vm;
try {
store(parse_command_line(argv.size() - 1, argv.data(), options), vm);
notify(vm);
} catch (po::error const& e) {
std::cerr << e.what() << std::endl;
options.print(std::cerr);
return 1;
}
}
印刷
unrecognised option '--oops'
Allowed options:
--opt
虽然没有图表,但有一种错误参考:https://www.boost.org/doc/libs/1_84_0/doc/html/program_options/reference.html#header.boost.program_options.errors_hpp
各个类型确实提到了目的,例如:“库中所有错误的基类”)