- 异常处理的基本思想;实际的资源分配操作失败时,异常为从分配资源的代码转向处理错误状态的代码提供一种表达方式。
- 异常处理的实现;C++异常处理用到的关键字有try、throw和catch;围绕它们的执行过程及异常接口声明;
- 定义自己的异常类;能够分别用不同的类型来标识每一种可能出现的异常情况;
设计步骤:
- 1.定义一个函数 ALLisnum(string)通过输入字符串长度,判断输入的小时与分钟是否为合理范围内的数值;
-
bool ALLisNUM(string str) { for(int i=0;i<str.size();i++) { int tmp=(int)str[i]; if(tmp>='0'&&tmp<='9'){ continue; } else{ return false; } } return true; }
2.定义一个名为TimeMistake的异常类,处理用户输入的时间;
-
class TimeMistake { private: string message; public: TimeMistake(){ } TimeMistake(string s) { message = s; } string getmes() { return message; } };
3.声明一个overtime的类,处理异常时间;
-
class overTime{ };
4.定义一个检测异常的函数void test();输入时间后,先调用ALLisNUM()函数判断是否有意义;为有效输入然后再执行时间转换;
-
void test() { string h,m; string a="AM"; int hour,minute; cout<<"input hour:"; cin>>h; if(!ALLisNUM(h))throw TimeMistake("meaningless string for hour."); else { hour = atoi(h.c_str()); if(hour>24||hour<0){ throw overTime(); } else if(hour>12){ hour-=12; a="PM"; } } cout<<"\ninput minute:"; cin>>m; if(!ALLisNUM(m))throw TimeMistake("meaningless string for minute."); else{ minute = atoi(m.c_str()); if(minute>59||minute<0)throw overTime(); } cout<<endl<<hour<<":"<<minute<<a<<endl; }
5.定义一个处理异常的函数void handler();又由函数handler()调用函数test();
-
void handler() { try{ test(); } catch(TimeMistake e){ cout<<e.getmes()<<endl; } catch(overTime){ cout<<"the number is out of the range.\n"; } }
6.主函数main()调用函数handler(),再由handler()调用函数test();最后输出显示程序结束end of program.
-
int main() { handler(); cout<<"end of program"; return 0; }
完整代码:
-
#include<iostream>
#include<string>
#include<sstream>
#include<stdlib.h>
using namespace std;
bool ALLisNUM(string str)
{
for(int i=0;i<str.size();i++)
{
int tmp=(int)str[i];
if(tmp>='0'&&tmp<='9'){
continue;
}
else{
return false;
}
}
return true;
}
class TimeMistake
{
private:
string message;
public:
TimeMistake(){ }
TimeMistake(string s)
{
message = s;
}
string getmes()
{
return message;
}
};
class overTime{
};
void test()
{
string h,m;
string a="AM";
int hour,minute;
cout<<"input hour:";
cin>>h;
if(!ALLisNUM(h))throw TimeMistake("meaningless string for hour.");
else
{
hour = atoi(h.c_str());
if(hour>24||hour<0){
throw overTime();
}
else if(hour>12){
hour-=12;
a="PM";
}
}
cout<<"\ninput minute:";
cin>>m;
if(!ALLisNUM(m))throw TimeMistake("meaningless string for minute.");
else{
minute = atoi(m.c_str());
if(minute>59||minute<0)throw overTime();
}
cout<<endl<<hour<<":"<<minute<<a<<endl;
}
void handler()
{
try{
test();
}
catch(TimeMistake e){
cout<<e.getmes()<<endl;
}
catch(overTime){
cout<<"the number is out of the range.\n";
}
}
int main()
{
handler();
cout<<"end of program";
return 0;
}
运行结果:
1)输入无效字符:输入小时one,输入分钟ba;看运行结果是否显示字符无意义(meaningless string for minute.);
2)输入非法时间,例如小时大于24,分钟大于59,看结果是否显示为数值超出实际时间的范围(the number is out of the range.);
3)输入一个在上午时间段(AM)内的数值,得到输出结果;
4)输入一个在下午时间段(PM)内的数值,转换小时后得到输出结果;