【问题标题】:try/catch throws errortry/catch 抛出错误
【发布时间】:2011-11-21 09:16:57
【问题描述】:

在来自 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

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

【问题讨论】:

  • 请注意"error"char[6] 的右值,它将绑定到const char[6]const char*,但IMO 不应绑定到char*。 (IOW,您的异常不会被捕获。)
  • 使用异常处理格式错误的用户输入对我来说听起来像是滥用;我建议宁愿阅读std::string,然后使用bool isInteger( const std::string &amp;s ) 之类的函数来根据您的格式要求验证给定的输入确实是一个整数。
  • 扔不是来自std::exception的东西也是一种糟糕的形式。

标签: c++ exception try-catch


【解决方案1】:

您也在检测 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).

试试这个:

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

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

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;
 } 

【讨论】:

  • 添加了“良好实践”异常处理示例,另见boost.org/community/error_handling.html
  • @user1035927:你没有,你设置了异常掩码之前进入循环。处理错误后,您可能需要致电.clear()
  • sehe,非常感谢您的帮助。我似乎通过放置条件来让它工作: if(cin.eof()) break;这样做是否明智?
  • @user1035927:我会说,不。基本原理:您正在使循环中的控制流进一步复杂化,该循环已经比所需时间长了大约 3 倍。当然,它会做你想做的事,你的编码风格取决于你。只要记住好心人说的话:)
  • "error" 不是整数类型。也许您的意思是“原始”类型?但这也不是很准确。您希望您的异常专门来自 std::exception
【解决方案2】:

我会说这是因为你总是返回到cin &gt;&gt; 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";
}

毫无疑问,您会看到七行输出,然后是抛出的错误。

【讨论】:

    【解决方案3】:

    因为它达到了EOF?输入中有 5 个正整数,乘以 0(无输出),然后到达 EOF。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2012-06-06
      • 2018-12-20
      • 2010-11-09
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多