C++ 多对象异常处理
代码不会转到C++ 多对象异常处理,c++,exception,C++,Exception,代码不会转到try语句中的第二行。请帮我找出错误 它还应该检查第二个对象 根据问题,该程序应检查所有对象的异常 #include <iostream> using namespace std; #include <cstring> class user { private: string username,pass; public: user() { username='0'; pass='0'; }
try
语句中的第二行。请帮我找出错误
它还应该检查第二个对象
根据问题,该程序应检查所有对象的异常
#include <iostream>
using namespace std;
#include <cstring>
class user
{
private:
string username,pass;
public:
user()
{
username='0';
pass='0';
}
void getdata()
{
cout<<"enter the username"<<endl;
cin>>username;
cout<<"enter password"<<endl;
cin>>pass;
float x=pass.length();
if(x<6)
{
throw 1;
}
int i=0,count=0;
while ( i<=x)
{
if(pass[i]>=48&&pass[i]<=57)
{
count=1;
break;
}
else
{
i++;
}
}
if(count==0)
throw "password does not contain a number ";
}
};
int main()
{
user a1,a2;
try
{
a1.getdata();
a2.getdata();
}
catch(int i)
{
cout<<"exception caught"<<endl<<"length of password less than 6 numbers "<<endl;
}
catch(char const* s){
cout<<"exception caught"<<endl<<s<<endl;
}
return 0;
}
#包括
使用名称空间std;
#包括
类用户
{
私人:
字符串用户名,pass;
公众:
用户()
{
用户名='0';
pass='0';
}
void getdata()
{
coutUnrelated,但我很好奇:float x=pass.length();
-您选择float
作为应该是std::size\u t
?不管怎样,一旦a1.getdata()
抛出,它就会抛出a2.getdata()
call。也就是说,它不会被调用;您直接转到catch处理程序,转储消息,然后完全按照编写的代码退出main
。如果要重试,您需要一个循环(以这种或那种方式)。代码按设计工作。您试图解决的实际问题是什么?是否希望a2.getdata()
即使a1.getdata()
抛出也要执行吗?如果是这样,那么您需要将a2.getdata()
移到之外,在最后一次捕获之后尝试。另外,在循环超出密码的范围时,请注意。