未捕获非整数输入异常

Sab*_*ggi 5 c++ runtime-error exception try-catch

我正在尝试在 C++ 中学习和创建异常,但是对于使用 ios::failbit 的 cin 异常,仅使用一个 catch 而不是另一个。

下面的代码仅使用整数除法,并在用户输入 0 进行除法以及输入非整数(例如单词)时创建抛出异常。

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
   int userNum;
   int divNum;
   int result;
   cin.exceptions(ios::failbit);       // Allow cin to throw exceptions

   try {
      
      cin >> userNum >> divNum;
      
      if (divNum <= 0) {
         throw runtime_error("Divide by zero!");
      }
      
         result = userNum / divNum;
         cout << result << endl;  
      
   }
   //why output is only printing RUNTIME EXCEPTION and will not print INPUT EXCEPTION?
   catch (const runtime_error &excpt) {
      cout << "Runtime Exception: " << excpt.what() << endl;
   }
   
   catch (const ios_base::failure &excpt) {
        cout<<"Input Exception: "<< excpt.what() << endl;
   }
   
   

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码运行时遇到的唯一问题是输入非整数时没有选择正确的错误。除此之外,所有其他测试都运行良好。

我尝试从两个捕获中删除 const ,但问题仍然存在。

让我知道我应该更改哪些内容来纠正代码以及您建议的任何改进。

Ted*_*gmo 8

这是因为,从 C++11 开始,ios_base::failure继承自runtime_error(via system_error),所以你的第一个catch捕获ios_base::failure也会捕获。

解决方案是交换 es 的顺序,catch以便更通用的runtime_error成为后备。