cin and try/catch

cin and try/catch

本文关键字:catch try and cin      更新时间:2023-10-16

我有这个简单的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*