【发布时间】:2013-10-24 16:33:38
【问题描述】:
我只是在学习如何在 C++ 中使用异常,并且在我的“测试”代码中遇到了奇怪的行为。 (请原谅像这样的过于愚蠢的问题......这不是缺乏研究/努力,只是缺乏经验!)如果我只是捕捉到例外DivideByZero 它工作正常。
但是引入第二个异常StupidQuestion 会使代码无法完全按照我的预期工作。我是如何在下面写的.但是,如果我输入 a=3 和 b=1,程序将重定向到 DivideByZero try 子句而不是 StupidQuestion 子句。不过,奇怪的是,divide 似乎确实在抛出 StupidQuestion(参见 cout 声明),但它并不正确,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 和 StupidQuestion 都是 int 类型有关,所以我更改了代码以使 StupidQuestion 的类型为 char 而不是 int。 (所以:const char StupidQuestion='F'; 和 catch(char StupidQuestion) 是上面唯一改变的东西)而且效果很好。
当两个异常具有相同的类型 (int) 时,为什么上面的代码不起作用?
【问题讨论】:
-
异常是按类型而不是按名称捕获的。所以两者都是 int 类型,第一个处理程序将捕获它们。如果您想区分它们,请将第二个设置为不同的类型。
-
@Duck:这将是我赞成的答案。
-
有什么理由不创建从异常继承的类并改用这些类?这比抛出随机类型更好地遵循模式