1

我已经用 expat 解析器注册了三个处理程序: - start -end - text

从主程序中,我读取 xml 文件,对其进行缓冲并调用 XML_Parse API。像这样的东西:

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

如果 XML_Parse 在失败时返回 0,则从内部抛出异常 if。它被内部捕获块捕获。

这是我的问题:如果在解析期间从任何处理程序中抛出用户定义的异常,那会在外部 catch 中捕获吗?

如果是,它实际上并没有发生在我的代码中。相反,它正在转储核心和堆栈显示 throw 导致 std:terminate。在从 HANDLERS 抛出异常之前,我是否必须执行其他任何操作。

谢谢。

4

3 回答 3

0

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.

于 2011-10-27T12:43:08.447 回答
0

你必须非常小心。(它在我正在处理的一些代码中导致了一些非常难以追踪的问题。)。在我的情况下,我必须使用的 expat 库不是使用 gcc 中所需的异常标志构建的,并且由于 expat 是 C(而不是 C++),它不知道如何处理异常 - 当发生异常时,应用程序刚刚终止.

但是,如果您可以使用正确的 gcc 标志构建 expat,那么一切都应该没问题。(重建 expat 对我来说是不可能的,所以我转而使用 libxml2 进行 DOM 解析)。

于 2011-10-27T13:45:10.227 回答
0

如果你从一个try{/*stuff*/}块中抛出一个异常并且throw嵌套很深,堆栈将一直展开到匹配的外部catch(...)函数。如果您的处理程序已分配堆内存,您将需要通过使用shared_ptr<>或删除来明确和小心地处理它。如果您的处理程序在try块内,则异常应该正常运行。

于 2011-10-27T13:27:38.833 回答