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

来源:互联网 发布:淘宝商品被投诉假货 编辑:程序博客网 时间:2024/05/16 08:12

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 clearfriend 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 exceptionif (!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;elsecout << "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学习版上运行的结果。