C++异常处理-具体示例

C++ Exception Handling - Concrete Example

本文关键字:-具 异常处理 C++      更新时间:2023-10-16

我有这个程序(部分程序未发布):

//Includes and functions
int main(int argc, char *argv[])
{
    ifstream loc("achievements.loc", ios::binary);
    getline(loc, header, static_cast<char>(1));
    loc.seekg(15, ios::cur);
    loc.read(reinterpret_cast<char*>(&subdirs), sizeof(subdirs));

    for( int i = 0; i < nstrings; i++ )
    {
        loc.read(reinterpret_cast<char*>(&strid), sizeof(strid));
        loc.read(reinterpret_cast<char*>(&stroffset), sizeof(stroffset));
        curoffset = loc.tellg();
        loc.seekg(strcodesbeg+16+stroffset);
        getline(loc, codestring, '');
        loc.seekg(curoffset);
    }
}

如果出现以下情况,我想终止程序:-文件未打开;-getline获取的头字符串不等于"string";-任何读取功能失败;-任一seekg失败;-跨步,与1234不匹配。

如何使用C++异常来完成此操作?我应该使用单个try{}catch(...){}块来创建函数,例如,读取数据并在失败时发送EOF_REACHED,还是使用try{}catch(var e){}catch(var2 e){}class或任何其他方式?

我理解简单函数中异常的概念,但当有更大的程序时,它会变得复杂。

我没有发现太多在主函数中显式使用try-catch块的c++源代码,但有例外。这怎么可能?

最详细的方法是对一个特定的异常进行子类化,该异常将为您提供有关所发生事情的一些上下文,例如:

class FileNotOpenedException : public std::runtime_error {};
int main(int argc, char *argv[])
{
   try
   {
      ifstream loc("achievements.loc", ios::binary);
      if(!loc.is_open())
         throw FileNotOpenedException;
      // ...
   }
   catch(const FileNotOpenedException& e)
   {
      // ...
   }
}

但是,请注意,对预期的错误条件使用异常并不一定是好的做法。异常应该只用于真正的"异常"情况,这是程序中完全出乎意料的情况,您无法在特定范围内从中恢复。上面没有打开的文件就是一个坏例子。然而,失败的CCD_ 5或CCD_ 6功能之一可能更合适。

也就是说,你可以按照自己的要求去做,上面是一个方法的例子。