C++ 抛出并捕获多个异常

// Project20161020.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<exception>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
/**
抛出并捕获多个异常
*/
void readIntegerFile(const string& fileName, vector<int> &dest)
{
	ifstream istr;
	int temp;
	istr.open(fileName);
	if (istr.fail())
	{
		throw runtime_error("Unable to open the file");
	}
	while (istr >> temp)
	{
		dest.push_back(temp);
	}
	if (!istr.eof()){
		//We did not reach the end-of-file
		//This means that some error occurred while reading the file
		//Throw an exception
		//文件结尾是非数字 则抛出
		throw runtime_error("Error reading the file.");
	}
}
int main()
{
	vector<int> myInts;
	const string& fileName = "C:/Users/Administrator/Desktop/IntegerFile.txt";
	try {
		readIntegerFile(fileName, myInts);
	}
	catch (const exception e) {
		cerr << e.what() << endl;
		return 1;
	}
	for (const auto element : myInts)
	{
		cout << element << " ";
	}
	cout << endl;
    return 0;
}



#include "stdafx.h"
#include<iostream>
#include<stdexcept>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
/**
   也可以让readIntegerFile()抛出两种不同类型的异常。以下是实现
   如果不能打开文件,则抛出invalid_argument类异常对象,如果无法读取整数,就抛出runtime_error类对象。
   invalid_argument和runtime_error都是定义在<stdexcept>头文件中的类
*/
void readIntegerFile(const string& fileName, vector<int> &dest)
{
	ifstream istr;
	int temp;
	istr.open(fileName);
	if (istr.fail())
	{
		throw invalid_argument("Unable to open the file");
	}
	while (istr >> temp)
	{
		dest.push_back(temp);
	}
	if (!istr.eof()) {
		//We did not reach the end-of-file
		//This means that some error occurred while reading the file
		//Throw an exception
		//文件结尾是非数字 则抛出
		throw runtime_error("Error reading the file.");
	}
}
int main()
{
	vector<int> myInts;
	const string& fileName = "C:/Users/Administrator/Desktop/IntegerFile.txt";
	//main()函数可以用两个catch语句捕获invalid_argument和runtime_error
	try {
		readIntegerFile(fileName, myInts);
	}
	catch (const invalid_argument& e) {
		cerr << e.what() << endl;
		return 1;
	}
	catch (const runtime_error& e) {
		cerr << e.what() << endl;
		return 1;
	}
	for (const auto&element : myInts) 
	{
		cout << element << " ";
	}
	cout << endl;
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值