简体   繁体   中英

Expat parser - c++ -Exception handling

I have registered three handlers with expat parser: - start -end - text

And from the main program, I read the xml file, buffer it and invoke XML_Parse API. Something like this:

try {
if( ! XML_Parse (....))
{
   // throw user-defined expection here
}
catch(...)
{
}
} // end of try
catch(...)
{
 }

If XML_Parse returns 0 on failure, an exception is being thrown from inside if. And it is caught in inner catch block.

Here is my question: If the user-defined exception is thrown from any of the handlers during parsing, will that be caught in the outer catch ?

If yes, its actually not happening in my code. Instead, it is dumping core and stack shows that throw is leading to std:terminate. Do I have to perform anything else before throwing exceptions from HANDLERS.

Thanks.

You have a mismatch between try and catch : Each try block is followed by at least one catch block, but you have only one try . Maybe like this:

try
{
  // stuff before

  try
  {
    if (!parse())
    {
      // ...
    }
  }

  // further catch blocks?

  catch(...)
  {
    // may rethrow
  }

  // stuff after
}

Note that the anonymous catch(...) isn't usually very good design - you either know what you expect and can handle, or you don't need to catch it. About the only useful thing for an anonymous catch to do is to log the exception and rethrow it.

If you throw an exception from within a try{/*stuff*/} block and the throw was deeply nested, the stack will unwind all the way to the matching outer catch(...) function. If your handlers had assigned heap memory, you will need to deal with that either by using shared_ptr<> or deleting explicitly and carefully . If your handlers were inside the try block, then the exception should behave as normal.

You have to be very careful with this. (It caused some very hard to track down problems in some code I was working on.). In my case the expat libs I had to use were not built using the required exception flags in gcc, and since expat is C (rather than C++) it didn't know what to do with the exceptions - when one occurred the application just terminated.

However if you can build expat with the right gcc flags all should be OK. (Rebuilding expat wasn't possible for me so I switched to DOM parsing using libxml2 instead).

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