C++ 异常处理-2

#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块。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值