解釋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學習版上運行的結果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章