运行下面的代码,将出现什么情况?( )
double hmean(double a, double b) {
if (a == -b)
throw runtime_error("Runtime error occurred");
return 2.0*a*b/(a + b);
}
int main() {
double x = 10;
double y = -10;
try {
int result = hmean(x, y);
cout << "hmean: " << result << endl;
}
catch (const runtime_error& e) {
cout << "Caught: " << e.what() << endl;
}
catch (...) {
cout << "Caught an unknown exception." << endl;
}
return 0;
}答案A。>=是大于等于比较运算符,>>=是右移赋值运算符(a>>=3等价于a=a>>3)。两者都是合法的C++运算符。
>=是右移赋值运算符,不是比较运算符。a>>=3相当于a=a>>3,将a右移3位。
【考点】异常抛出|try-catch 匹配|runtime_error
1. 🎯 考纲定位 GESP 四级 C++ 模块第 7 章"异常处理"第 3 节。命题人把"逻辑条件直接抛异常"塞进试卷,就是要卡住"以为异常只在库函数里用"的考生。
2. 🧠 解题思维 先跑逻辑:a=10, b=-10 满足 a==-b,立刻 throw runtime_error。try 块遇到异常,控制权跳到第一个 catch (const runtime_error&),执行 e.what() 返回构造函数里的 "Runtime error occurred"。
3. 🪤 陷阱拆解 选项 B 是"没匹配到类型"(比如抛 int 却 catch runtime_error),C 是"没 caught 且没 default catch"(会走 std::terminate),D 是编译错误(代码本身没问题)。最阴险的是把"条件判断"偷换成"抛异常",让你以为只是普通 return。
4. 🔄 反命题思维 把条件改成 if (a == 0),抛 runtime_error 还是 std::out_of_range?catch 块里 e.what() 输出什么?如果 catch 类型写成 catch (int&),会发生什么?刷到这类题先问"抛了什么、catch 了什么、类型是否匹配"。