C++的异常捕捉

newman0708 2005-03-27 11:13:16
int act;
while(act!=9){
cout<<"\nEnter your action:";
cin>>act;
try{

//在这里不知道怎么去捕捉异常
//当输入为字符或者是汉字时,就不正常了,
//为了防止这种现象的出现,我想做一个异常捕捉。

//throw "Wrong Input!";
}
catch(string msg){
cout<<"Error: "<<msg<<endl;
continue;
}

...


希望各位能帮忙,谢谢!
...全文
166 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Salam2001 2005-03-27
  • 打赏
  • 举报
回复
int act;

do{
cout << "\nEnter your action:";
try
{
cin >> act;
if( !cin ) // cin 本身有类型检查功能,类型不匹配时会设置 cin 的 failbit
throw string( "Wrong Input!" );
}
catch( string msg )
{
cout << "Error: " << msg << endl;
cin.clear();
while( cin.get() != '\n' ); // get rid of extra characters
continue;
}
}while( act != 9 );
富莱工作室 2005-03-27
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;

int main()
{
char act;
while(act!='9')
{
cout<<"\nEnter your action:";

try
{
cin>>act;
if(act < 0x30 || act > 0x39)
{
string msg("Wrong Input");
throw(msg);
}
}

catch(string msg)
{
cout<<"Error: "<<msg<<endl;
}
}


return 0;

}

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧