c++ - xml解析的错误处理

标签 c++ refactoring error-handling xml-parsing

我正在使用 tinyxml 来解析 xml 文件,我发现此处的错误处理适用于箭头代码。我们的错误处理只是向文件报告一条消息。

这是一个例子:

  const TiXmlElement *objectType = dataRoot->FirstChildElement( "game_object" );
  if ( objectType ) {
    do {
      const char *path = objectType->Attribute( "path" );
      if ( path ) {
        const TiXmlElement *instance = objectType->FirstChildElement( "instance" ); 
        if ( instance ) {
          do {
            int x, y = 0; 
            instance->QueryIntAttribute( "x", &x );
            instance->QueryIntAttribute( "y", &y );
            if ( x >= 0 && y >= 0 ) {
              AddGameObject( new GameObject( path, x, y ));
            } else {
              LogErr( "Tile location negative for GameObject in state file." );
              return false;
            }
          } while ( instance = instance->NextSiblingElement( "instance" ));
        } else {
          LogErr( "No instances specified for GameObject in state file." );
          return false;
        }
      } else {
        LogErr( "No path specified for GameObject in state file." );
        return false;
      }
    } while ( objectType = objectType->NextSiblingElement( "game_object" ));
  } else {
    LogErr( "No game_object specified in <game_objects>. Thus, not necessary." );
    return false;
  }
  return true;

我并没有为此大发雷霆,但如果有人能想出一种更简洁的方法来实现这一点,我们将不胜感激。

附言异常(exception)不是一种选择。

编辑:

这样的东西会更好吗?

if ( !path ) {
  // Handle error, return false
}
// Continue

这消除了箭头代码,但箭头代码将所有错误记录放在一个地方。

最佳答案

使用返回值作为错误码只会导致这样的代码,无法改进。一种稍微简洁的方法是使用 goto 将所有错误处理分组到一个 block 中并减少 block 的嵌套。

但这并没有解决实际问题,即使用返回值作为错误代码。在 C 中,没有其他选择,但在 C++ 中,异常是可用的,应该使用。如果它们不是一种选择,那么您就会受困于现有的东西。

关于c++ - xml解析的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3172451/

相关文章:

css - 使用 SASS 干燥多个 3 列列表

c# - 如何在.net core 中记录未处理的异常

c++ - 为什么以下Linux目录有效

c++ - 累积 double vs 整数

python - SQLAlchemy 中的条件过滤

php - 基于应用程序的错误记录/处理?

powershell - 尝试/捕获非法字符

c++ - 如何在 Qt 上实现 GDAL 库?

c++ - 64位部署

asp.net-mvc - 如何让 Visual Studio 也对 View /页面执行重构?