在boost :: property_tree :: read_xml中捕获异常

时间:2014-10-10 13:24:36

标签: c++ boost

我正在尝试捕获boost::property_tree::xml_parser::read_xml引发的异常。这是我的示例程序:

 #include <iostream>
 #include <boost/property_tree/ptree.hpp>
 #include <boost/property_tree/xml_parser.hpp>
 int main(int argc, char** argv){
      boost::property_tree::ptree pt;
      std::cout<<"123123"<<std::endl;
      try{
        std::cout<<"Reading "<<argv[1]<<std::endl;
        read_xml(argv[1], pt);
      }
      catch(const boost::property_tree::xml_parser::xml_parser_error& ex){
        std::cout<<argv[1]<<" failed, reading "<<argv[2]<<std::endl;
        read_xml(argv[2], pt);
      }
 }

输出结果为:

123123
Reading 123.xml
[1]    97028 abort      ./a.out 123.xml 345.xml

我做错了什么?显然没有抓住异常。我还尝试通过(...)捕捉所有内容并捕捉std::exception以及boost::exception。在所有情况下,结果都是相同的。根据boost文档,应抛出xml_parser_error。我的提升版本是1.54。

一点点更新: 当我不尝试执行read_xml(“notAValidFilePAth”,pt)时,我得到了

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::property_tree::xml_parser::xml_parser_error> >'
  what():  123.xml: cannot open file

当我用gdb运行它时,我得到:

Reading terminate called after throwing an instance of 
'boost::exception_detail::clone_impl<
       boost::exception_detail::error_info_injector<
           boost::property_tree::xml_parser::xml_parser_error> >'
  what():  PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/MacGPG2/bin:/opt/local/bin:/usr/texbin:/Users/weidenka/bin: 
 cannot open file
 Program received signal SIGABRT, Aborted.
    0x00007fff8a31b866 in __pthread_kill ()

#0  0x00007fff8a31b866 in __pthread_kill ()
#1  0x00007fff86c9f35c in pthread_kill ()
#2  0x00007fff86240b1a in abort ()
#3  0x00000001005547d5 in __gnu_cxx::__verbose_terminate_handler ()

提前致谢!

祝福,彼得

1 个答案:

答案 0 :(得分:0)

这是你的问题:

    read_xml(argv[2], pt);

回退读取操作没有防止抛出异常,因此当此时发生异常时,程序会终止而不会刷新iostreams缓冲区。