提供的示例代码返回一个随机数,即使在抛出异常之后也是如此(提供的代码)
The sample code provided returns a random number, even after throwing an exception (code provided)
我有一个修改和抛出异常处理的示例代码。问题是,即使在我抛出异常之后,代码仍然返回一个随机的0。我花了一些时间试图弄清楚为什么我仍然有一个0返回,但我找不到答案。有人知道为什么代码是这样的吗?
#include <stdexcept>
#include <iostream>
#include <string>
using namespace std;
struct myException_Product_Not_Found : exception
{
virtual const char* what() const throw() {
return "Product not found";
}
} myExcept_Prod_Not_Found;
int getProductID(int ids[], string names[], int numProducts, string target) {
for (int i=0; i<numProducts; i++) {
if(names[i] == target)
return ids[i];
}
try {
throw myExcept_Prod_Not_Found;
}
catch (exception& e) {
cout<<e.what()<<endl;
}
}
// Sample code to test the getProductID function
int main() {
int productIds[] = {4,5,8,10,13};
string products[] = {"computer","flash drive","mouse","printer","camera"};
cout << getProductID(productIds, products, 5, "computer") << endl;
cout << getProductID(productIds, products, 5, "laptop") << endl;
cout << getProductID(productIds, products, 5, "printer") << endl;
return 0;
}
getProductID
不会抛出异常。在getProductID
有机会抛出异常之前,您捕获了抛出的异常。因此,你返回……好了,什么都没有。不调用return
,函数结束
如果您已经打开了编译器的警告*(应该这样做),编译器应该用control reaches end of non-void function
这样的消息发出警告。在这个实例中,g++
似乎返回0,但返回0可能是未定义的行为。
如果你想让一个函数抛出异常,不要捕捉你在函数内部抛出的异常。把接环移到外面。
int getProductID(...) {
...
throw myExcept_Prod_Not_Found;
}
string product = "computer";
try {
cout << getProductID(productIds, products, 5, product) << endl;
} catch (exception& e) {
cout << "Can't find product id for " << product << ": " << e.what() << endl;
}
& # 42;本;要在g++
中打开警告,-Wall
是一个很好的起点。@Tomalak Geret'kal建议-Wall -Wextra -std=c++98 -pedantic
或-Wall -Wextra -std=c++0x -pedantic
try {
throw myExcept_Prod_Not_Found;
}
catch (exception& e) {
cout<<e.what()<<endl;
}
在这里你抛出了一个异常,然后立即捕获它。异常消息输出到控制台,然后函数继续正常执行…除非你没有值可以返回。
因此,该函数调用的结果是未指定的,并且您看到内存中的一些任意垃圾以及调用未定义行为。相反,只要让异常通过不捕获它而直接传播到调用堆栈:它将导致程序终止(顺便说一句,可能没有实际展开):
throw myExcept_Prod_Not_Found;
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- GCC对可能有效的代码抛出init list生存期警告
- 函数如何通知用户它基于函数原型抛出异常?
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- VisualStudios 会抛出异常,而代码块不会 [C++]
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- ZMQ::send() 抛出异常并终止 QNX 进程.为什么以及如何从中恢复?
- new(std::nothrow) int[n] 抛出异常
- 为什么g_object_set抛出异常(vcruntime140.dll)?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- C++子线程抛出异常
- 我们应该在抛出异常之前取消分配内存吗
- 有没有一种方法可以让OpenCLC++绑定为所有错误抛出异常
- 是否可以对构造函数抛出异常的对象进行异常处理,该对象的异常处理接近其基于堆栈的代码创建
- 在xmemory代码的深处抛出C++异常
- 提供的示例代码返回一个随机数,即使在抛出异常之后也是如此(提供的代码)
- 为什么当我的lua代码抛出错误时,我无法捕获luabind::error异常?
- 如果 c 代码"through"抛出异常会发生什么?
- 演示代码抛出out_of_range异常,但我不知道为什么