gpt4 book ai didi

c++ - Catch 子句没有捕获对吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:44:00 25 4
gpt4 key购买 nike

我刚刚学习如何在 C++ 中使用异常,并且在我的“测试”代码中遇到了奇怪的行为。 (请原谅像这样过于愚蠢的问题......这不是缺乏研究/努力,只是缺乏经验!)如果我只是捕获异常 DivideByZero 它工作正常。

但是引入第二个异常 StupidQuestion 使得代码无法完全按照我的预期工作。我是如何在下面写的,我认为它应该在需要时处理 DivideByZero 异常,如果没有则检查 StupidQuestion 是否发生,如果没有则返回try 子句并打印正常结果。但是如果我输入,比方说,a=3b=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;
}

我想知道这是否与 DivideByZeroStupidQuestion 都是 int 类型有关,所以我更改了使 StupidQuestion 成为 char 类型而不是 int 类型的代码。 (所以:const char StupidQuestion='F';catch(char StupidQuestion) 实际上是上面唯一改变的东西)而且它工作正常。

当两个异常具有相同的类型 (int) 时,为什么上面的代码不工作?

最佳答案

代替这个

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 子句中的变量名正在创建一个新的局部变量,该变量与同名的全局常量无关。

另请注意,无法只捕获一个错误编号...但您可以像我展示的那样重新抛出未知错误。

关于c++ - Catch 子句没有捕获对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19571610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com