我正在学习如何在C++中使用异常,并且在我的“测试”代码中遇到了奇怪的行为。(请原谅这类过于愚蠢的问题.这不是缺乏研究/努力,只是缺乏经验!)如果我只捕捉到异常DivideByZero,它就可以正常工作。
但是,引入第二个例外,StupidQuestion使代码不能完全按照我的预期工作。我在下面如何编写它,我认为如果需要的话,它应该处理DivideByZero异常,如果没有,那么检查是否发生了StupidQuestion,如果不是,只返回try子句并打印正常的结果。但是,如果输入,例如a=3和b=1,程序将重定向到DivideByZero try子句,而不是StupidQuestion try子句。然而,奇怪的是,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)时,上面的代码为什么不能工作?
发布于 2013-10-24 16:40:40
而不是这个
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;
}你在找
catch (int errval) {
if (errval == DivideByZero) {
cout << "ERROR: Divide by zero!" << endl;
}
else if (errval == StupidQuestion) {
cout << "ERROR: You are an idiot for asking a stupid question like that!" << endl;
}
else {
throw; // for other errors, keep searching for a handler
}
}catch 子句中的变量名正在创建一个新的局部变量,它与同名的全局常量没有关系。
还请注意,不可能只捕获一个错误号.但如我所示,您可以重新抛出未知的错误。
发布于 2013-10-24 16:38:13
catch(int DivideByZero) { }
catch(int StupidQuestion) { }两个catch块都捕获int,它们只是命名不同。只有第一个可以被输入,第二个是死代码。
发布于 2021-08-28 14:07:57
在为异常类型选择处理程序时,不考虑值或地址(由于异常的工作方式而在这里根本不适用变量的地址),编译后也不存在变量的名称。总是为异常选择第一个适当的处理程序。
请看我对另一个问题的回答,以获得详细信息:https://stackoverflow.com/a/45436594/1790694
https://stackoverflow.com/questions/19571610
复制相似问题