try/catch抛出错误

use*_*927 2 c++ exception try-catch

在stackoverflow的好撒玛利亚人的帮助下,当来自用户的输入不是整数时,我已经到了以下代码来捕获异常:

signed int num;

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

现在假设该程序被调用:checkint.如果我通过重定向文本文件中的输入来调用程序,请输入:input.txt,其中包含以下内容:12 5 12 0 3 2 0

checkint <input.txt
Run Code Online (Sandbox Code Playgroud)

输出:我得到以下输出:

number greater than 0
number greater than 0
number greater than 0
number greater than 0
number greater than 0
error
Run Code Online (Sandbox Code Playgroud)

当文件中的所有输入都是整数时,为什么它最终会抛出错误?谢谢

seh*_*ehe 5

你也在检测eof.阅读上.good(),.bad(),.eof().fail():http://www.cplusplus.com/reference/iostream/ios_base/iostate/

flag value  indicates
eofbit  End-Of-File reached while performing an extracting operation on an input stream.
failbit The last input operation failed because of an error related to the internal logic of the operation itself.
badbit  Error due to the failure of an input/output operation on the stream buffer.
goodbit No error. Represents the absence of all the above (the value zero).
Run Code Online (Sandbox Code Playgroud)

试试这个:

while(cin >> num)
{
    if(num>0){
        cout<<"number greater than 0"<<endl;
    }
}

// to reset the stream state on parse errors:
if (!cin.bad()) 
   cin.clear(); // if we stopped due to parsing errors, not bad stream state
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢获得例外,请尝试

cin.exceptions(istream::failbit | istream::badbit);
Run Code Online (Sandbox Code Playgroud)

松散的笔记:

  • 在异常模式下使用流不常见
  • 投掷原始类型并不常见.考虑写作

.

 #include <stdexcept>

 struct InputException : virtual std::exception 
 {  
     protected: InputException() {}
 };

 struct IntegerInputException : InputException 
 {
     char const* what() const throw() { return "IntegerInputException"; }
 };

 // ... 
 throw IntegerInputException();

 //
 try
 {
 } catch(const InputException& e)
 {
      std::cerr << "Input error: " << e.what() << std::endl;
 } 
Run Code Online (Sandbox Code Playgroud)