cin 和 try/catch
我有这个简单的 try catch 来抛出 cin 异常,但它从不抛出异常。
while(cin>>num) {
try {
if(cin.fail()) {
throw "error";
}
if(num>0) {
cout << "number greater than 0" << endl;
}
}
catch(char* error) {
cout << error << endl;
}
}
为什么它不抛出异常?
I have this simple try catch for throwing cin exceptions, but it never throws exceptions.
while(cin>>num) {
try {
if(cin.fail()) {
throw "error";
}
if(num>0) {
cout << "number greater than 0" << endl;
}
}
catch(char* error) {
cout << error << endl;
}
}
Why it is not throwing the exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
辛>> num return false,所以你的循环体根本不会被执行。
如果确实需要使用execption,
最好将try catch放在循环之外以获得更好的性能
cin >> num return false, so your loop body doesn't get executed at all.
If you really need to use execption
It's better to put the try catch outside of the loop to get better performance
字符串文字,例如“error”,与
char*
不匹配,它需要是const char*
String literals, like "error", do not match
char*
, it needs to beconst char*