C++异常处理-具体示例
C++ Exception Handling - Concrete Example
我有这个程序(部分程序未发布):
//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功能之一可能更合适。
也就是说,你可以按照自己的要求去做,上面是一个方法的例子。
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- C++执行期间的类成员函数错误/异常处理
- C++ 中未处理的异常处理程序
- 用户定义的异常处理
- C :ScopeGuard vs返回支票和异常处理
- 异常处理期间的类型解析