提供的示例代码返回一个随机数,即使在抛出异常之后(提供的代码) [英] The sample code provided returns a random number, even after throwing an exception (code provided)
问题描述
我有一个示例代码来修改和抛出异常处理。问题是甚至在我抛出异常后,代码仍然返回一个随机0.我花了一些时间,试图找出为什么我还有一个0返回,但我找不到答案。有没有人知道为什么代码的行为像这样?
I have a sample code to modify and throw exception handling. The problem is even after I threw an exception, the code still returns a random 0. I have spent some time trying to figure out why I still have a 0 returned but I could not find the answer. Does anyone have an idea why the code behaves like this?
#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
。
getProductID
doesn't throw an exception. You catch the exception you do throw before getProductID
has a chance to throw it. As such, you return ... well, nothing. The functions ends without you calling return
.
如果你打开了编译器的警告* do),编译器应该使用控制到非结束函数
的消息来警告。 g ++
在此实例中显示为返回零,但返回零可能是未定义的行为。
If you had turned on your compiler's warnings* (as should should be doing), the compiler should warn with a message like control reaches end of non-void function
. g++
appears to return zero in this instance, but returning zero is probably undefined behaviour.
抛出异常,不捕捉你抛出的异常在函数内部。将捕获移到外面。
If you want a function to throw an exception, don't catch the exception you've thrown inside of the function. Move the catch to the outside.
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;
}
*—要打开 g ++
中的警告, -Wall
是一个很好的起点。 @Tomalak Geret'kal建议 -Wall -Wextra -std = c ++ 98 -pedantic
或 -Wall -Wextra -std = c ++ 0x -pedantic
。
* — To turn on warnings in g++
, -Wall
is a good starting point. @Tomalak Geret'kal suggests -Wall -Wextra -std=c++98 -pedantic
or -Wall -Wextra -std=c++0x -pedantic
.
这篇关于提供的示例代码返回一个随机数,即使在抛出异常之后(提供的代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!