C++ 提供的示例代码返回一个随机数,即使在抛出异常后也是如此(提供的代码)
我有一个示例代码可以修改并抛出异常处理。问题是,即使我抛出了一个异常,代码仍然会返回一个随机的0。我花了一些时间试图找出为什么仍然返回0,但找不到答案。有人知道为什么代码会这样吗C++ 提供的示例代码返回一个随机数,即使在抛出异常后也是如此(提供的代码),c++,exception,C++,Exception,我有一个示例代码可以修改并抛出异常处理。问题是,即使我抛出了一个异常,代码仍然会返回一个随机的0。我花了一些时间试图找出为什么仍然返回0,但找不到答案。有人知道为什么代码会这样吗 #include <stdexcept> #include <iostream> #include <string> using namespace std; struct myException_Product_Not_Found : exception { vi
#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;
}
#包括
#包括
#包括
使用名称空间std;
未找到结构myException\产品\异常
{
虚拟常量char*what()常量throw(){
返回“未找到产品”;
}
}未找到myExcept_Prod_;
int getProductID(int-id[],字符串名称[],int-numProducts,字符串目标){
for(int i=0;igetProductID
不会引发异常。在getProductID
有机会引发异常之前,您捕获了您确实引发的异常。因此,您会返回……嗯,什么都没有。函数结束时不调用return
如果您打开了编译器的警告*(应该这样做),编译器应该发出警告消息,如control reaches end of non void function
g++
在本例中似乎返回零,但返回零可能是未定义的行为
如果希望函数引发异常,请不要捕获在函数内部引发的异常。请将捕获移到外部
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;
}
int getProductID(…){
...
抛出myExcept\u Prod\u未找到;
}
字符串product=“计算机”;
试一试{
cout Where is……示例代码!欢迎使用StackOverflow。您需要提供再现问题的最小代码,以便任何人都有机会帮助您。我哈哈大笑。然后我摇摇头。然后我哭了。如果它总是返回0,我不会说它是随机的。;)如果您不显示代码,我们无法帮助您识别代码中的错误。在极少数情况下,我们可能会帮助您对代码进行非常详细的描述,但您的描述并不有用。由于异常而死亡的代码不会返回,因此不可能返回零。然后出现了“随机0”的问题。如果它总是零,那么它是如何随机的?请包含一个最小的、可运行的问题演示。-Wall
更像是-Wsome
;它省略了许多警告。要真正得到很多警告,你应该使用“-Wall-Wextra-std=c++98-pedantic
”或“-Wall-Wextra-std=c++0x-pedantic
”。@Tomalak Ge雷特卡尔,谢谢,我已经把它纳入了答案中。
try {
throw myExcept_Prod_Not_Found;
}
catch (exception& e) {
cout<<e.what()<<endl;
}
throw myExcept_Prod_Not_Found;