我有一个修改和抛出异常处理的示例代码。问题是,即使在我抛出异常之后,代码仍然返回一个随机的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;