解释throw表达式和try块的使用方法的程序

throw表达式是用在try块中的。它用于抛出错误信息。throw抛出的错误信息被下面的catch函数接受,并且通过runtime_error类的成员函数what()返回throw关键字抛出的错误信息。下面是源程序。

Sales_item.h

#ifndef _SALES_ITEM_
#define _SALES_ITEM_

#include <string>
#include <iostream>

using std::string;
using std::istream;

class Sales_item
{
public:
	bool same_isbn(Sales_item& s)
	{return (isbn == s.isbn);}
	//this is not very clear
	friend istream& operator >>(istream& in, Sales_item& s)
	{
		in >> s.isbn;
		return in;
	}
private:
	string isbn;
};

#endif


main.cpp

#include <iostream>
#include <stdexcept>
#include "Sales_item.h"
using std::runtime_error;

using std::cin;
using std::cout;
using std::endl;
using std::cerr;

int main()
{
	Sales_item item1, item2;
	while (cin >> item1 >> item2)
	{
		try 
		{
			//execute code that will add the two Sales_item
			//if the addition fails, the code throw a runtime exception
			if (!item1.same_isbn(item2))
				throw runtime_error("Data must refer to the same ISBN! ");
			cout << "everything is OK! " << endl;
			break;
		}
		catch (runtime_error err)
		{
			cout << err.what() << endl;
			cout << "Try Again? Enter y or n. " << endl;
			char c;
			cin >> c;
			if (c == 'n')
				break;
			else
				cout << "Please try again! " << endl;
		}
	}
	cout << "the program will be stop! ";
	getchar();
	getchar();
	return 0;
}

 

2013年8月18日 对try块和throw表达式的用法的补充。

try块和throw表达式并不是非要一起成对使用的。throw表达式抛出的错误信息可以被try块中的catch语句接住并且通过what()成员函数输出throw输出的错误信息。但是,如果没有throw表达式catch语句就什么都接不到么?不是这样的。throw表达式是一种允许程序员自定义错误信息的表达式。系统同样还定义了一组标准异常。这些标准异常定义在exception等头文件中。也就是说,如果包含了相应的头文件而且在try语句中出现了同文件中定义的错误,那么catch语句就能接受到相应的错误信息。这类头文件包括:exception,stdexcept,new,type_info。这四种头文件的用法绝大多数我没有进行试验。只有stdexcept头文件中的overflow_error类做过实验。其他标准异常类的实验如果有机会再补充。关于overflow_error异常类的实验见下面的程序。

#include <stdexcept>			//stdexcept头文件中定义了overflow_error类
#include <iostream>
#include <cstdlib>			//cstdlib头文件中定义了EXIT_SUCCESS
#include <bitset>
using std::overflow_error;		//由于overflow_error不是系统关键字,所以一定要写using声明
using std::bitset;
using std::cout;
using std::endl;
int main()
{
	//用sizeof函数看看unsigned long类型的变量有多少位
	//实验的结果是4*8=32位
	int i = sizeof(unsigned long);
	bitset<50> b;
	b.set();
	try
	{
		//由于unsigned long类型的变量只有32位
		//50位,每一位都是1的变量b的大小超过了unsigned long类型表示范围
		//造成了溢出错误(overflow_error)
		unsigned long u = b.to_ulong();
	}
	catch (overflow_error err)
	{
		cout << err.what() << endl;
	}
	getchar();
	return EXIT_SUCCESS;
}


 

下图是上面程序在64位Windows7旗舰版Microsoft Visual C++ 2010学习版上运行的结果。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值