try / catch throws错误 [英] try/catch throws error

查看:185
本文介绍了try / catch throws错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在来自stackoverflow的好samaritans的帮助下,我来到下面的代码捕获异常,当用户的输入不是一个整数:

With the help from good samaritans from stackoverflow, I have come till the following code to catch exceptions when the input from user is not an integer:

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

Now assume the program is called: checkint. If I call the program by redirecting the input from a text file, say: input.txt, which has the following contents: 12 5 12 0 3 2 0

checkint <input.txt

输出:
我得到以下输出:

Output: I get the following output:

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

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

Why is it throwing the error in the end, when all the input in the file are integers? Thanks

推荐答案

阅读 .good() .bad() .eof / code>和 .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



如果您喜欢获取异常,尝试

If you prefer getting the exception, 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;
 } 

这篇关于try / catch throws错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆