cin and try/catch
cin and 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;
}
}
为什么不抛出异常?
cin>> num返回false,因此循环体根本不会执行。
如果你真的需要使用exception
while(true)
{
cin >> num;
try{
if(cin.fail()){
throw "error";
}
if(num>0){
cout<<"number greater than 0"<<endl;
}
}
catch( char* error){
cout<<error<<endl;
break;
}
}
最好将try catch放在循环之外以获得更好的性能
字符串字面值,如"error",不匹配char*
,需要匹配const char*
相关文章:
- 编译器是否必须始终删除 try-catch 块(如果它被证明是非抛出的)
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 我可以使用 try catch 语句来捕获任何错误而不是具体错误吗?
- 在大型应用程序的main上使用try-catch
- RapidXML 节点在 try catch 块中具有正确的值,但它在块外为 nullptr
- 提取 try-catch 时出现运行时错误
- std::unique_ptr 在 try-catch 块中未捕获取消引用异常
- 何时删除 try-catch 块中的指针
- 是否有理由大多数/所有 try-catch 示例只对 throw 语句使用 void 子函数
- 循环try..catch ..确保输入有效或使用控制语句
- 构造函数中的异常:init() 方法、指针、大型 try/catch 或
- C++ C2509 在讲师的定义中使用 try: - catch
- 为什么未达到的 try-catch 块会增加运行时时间
- 在 C++ 中使用 try-catch 进行删除 [] 或删除操作是否必要
- ex.nested try-catch中的什么()更改
- 为什么 c++ try-catch 块不能在 ubuntu 上与 g++ 一起使用?
- 格式化文件异常被 try catch 块忽略
- libpng错误不会被try/catch块捕获
- 在 C++ 和 C# 中使用 try/catch 的正确方法是什么?
- 如何使用catch try-catch