我只是在学习如何在 C++ 中使用异常,并且在我的“测试”代码中遇到了奇怪的行为。(请原谅像这样的过于愚蠢的问题......这不是缺乏研究/努力,只是缺乏经验!)如果我只是抓住例外DivideByZero,它就可以正常工作。
但是引入第二个异常StupidQuestion会使代码无法完全按照我的预期工作。我是如何在下面写的,我认为它应该在需要时处理DivideByZero异常,如果没有,则检查是否StupidQuestion发生,如果没有,则返回try子句并打印正常结果。但是如果我输入,比如说,a=3and b=1,程序会重定向到DivideByZero try子句而不是那个子句StupidQuestion。奇怪的是,虽然,divide似乎确实在抛出StupidQuestion(见 viacout声明),但它并没有抓住正确,正如cout声明的缺席所看到的那样。
#include <iostream>
#include <cstdlib>
using namespace std;
const int DivideByZero = 42;
const int StupidQuestion=1337;
float divide (int,int);
main(){
int a,b;
float c;
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denominator: ";
cin >> b;
try{
c = divide(a,b);
cout << "The answer is " << c << endl;
}
catch(int DivideByZero){
cout << "ERROR: Divide by zero!" << endl;
}
catch(int StupidQuestion){
cout << "But doesn't come over here...?" << endl;
cout << "ERROR: You are an idiot for asking a stupid question like that!" << endl;
}
system("PAUSE");
}
float divide(int a, int b){
if(b==0){
throw DivideByZero;
}
else if(b==1){
cout << "It goes correctly here...?" << endl;
throw StupidQuestion;
}
else return (float)a/b;
}
DivideByZero我想知道这是否与andStupidQuestion都是 type的事实有关int,所以我更改了代码以使 StupidQuestion 的类型为 char 而不是 int。(所以:const char StupidQuestion='F';并且catch(char StupidQuestion)真的是唯一从上面改变的东西)而且效果很好。
当两个异常具有相同的类型()时,为什么上面的代码不起作用int?