我正在尝试在 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) …Run Code Online (Sandbox Code Playgroud)