ошибка try / catch throws - PullRequest
       22

ошибка try / catch throws

2 голосов
/ 21 ноября 2011

С помощью добрых самаритян из 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;
   }
}

Теперь предположим, что программа называется: checkint.Если я вызываю программу, перенаправляя ввод из текстового файла, скажем: input.txt, который имеет следующее содержимое: 12 5 12 0 3 2 0

checkint <input.txt

Вывод: я получаю следующий вывод:

number greater than 0
number greater than 0
number greater than 0
number greater than 0
number greater than 0
error

Почему выдается ошибка в конце, когда все входные данные в файле являются целыми числами?Спасибо

Ответы [ 3 ]

5 голосов
/ 21 ноября 2011

вы тоже обнаруживаете.Читайте о .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).

Попробуйте:

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

Если вы предпочитаете получить исключение,try

cin.exceptions(istream::failbit | istream::badbit);

Свободные заметки:

  • использование потоков в режиме исключения не является обычной практикой
  • бросание примитивных типов не является обычной практикой.Попробуйте написать

.

 #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;
 } 
0 голосов
/ 21 ноября 2011

потому что он достиг EOF? У вас есть 5 положительных целых чисел на входе, два раза 0 (без вывода), и затем достигается EOF.

0 голосов
/ 21 ноября 2011

Я бы сказал, что это потому, что вы всегда возвращаетесь к выражению cin >> num даже после прочтения последнего целого числа.

Если вы измените:

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

в

if (num > 0) {
    cout << "number greater than 0\n";
} else {
    cout << "number less than or equal to 0\n";
}

Вы, без сомнения, увидите семь строк вывода, а затем выданную ошибку.

...