#include "stdafx.h"
#include<iostream>
#include<exception>
#include<vector>
#include<string>
#include<fstream>
using namespace std;
/**
文件打开失败问题
代码抛出一个std::exception类型的异常,这个类型需要包含<exception>头文件。
如果文件打开失败就会抛出 Unable to open file XXX 行
*/
void readIntegerFile(const string& fileName, vector<int>&dest)
{
ifstream istr;
int temp;
istr.open(fileName);
if (istr.fail())
{
throw exception();
}
while (istr >> temp)
{
dest.push_back(temp);
}
}
int main()
{
vector<int> myInts;
const string& fileName = "C:/Users/Administrator/Desktop/IntegerFile.txt";
try
{
readIntegerFile(fileName, myInts);
}
catch (const std::exception&)
{
cerr << "Unable to open file " << fileName << endl;
return 1;
}
for (const auto element : myInts)
{
cout << element << " ";
}
return 0;
}
txt文件
输出结果:
如果还编写了处理异常的代码,这种情况下抛出异常效果最好。异常处理是这样一种方法:"尝试"执行一块代码,并且用另一块代码响应可能发生的任何错误。在下
面的main()函数中,catch语句响应任何被try块抛出偶的exception类型异常,并输出错误消息。如果try块结束时没有抛出异常,catch块将被忽略。可以将try/catch
块当作if语句。如果在try块中抛出异常,就会执行catch块,否则就忽略catch块。