简体   繁体   中英

Catch exception in boost::property_tree::read_xml

I'm trying to catch exceptions that are raised by boost::property_tree::xml_parser::read_xml . Here is my example program:

 #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);
      }
 }

The output is:

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

What am I doing wrong? Obviously the exception isn't caught. I also tried to catch every thing via (...) and to catch std::exception as well as boost::exception . In all cases the result is the same. According to boost documentation a xml_parser_error should be thrown. My boost version is 1.54.

A Little update: When I don't try to just execute read_xml("notAValidFilePAth",pt), then I get

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

And when I run it with gdb I get:

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 ()

Thanks in advance!

Best wishes, Peter

This is your problem:

    read_xml(argv[2], pt);

The fallback read operation is not guarded against throwing an exception, so when an exception occurs at this point your program terminates without flushing the iostreams buffers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM