提供的示例代码返回一个随机数,即使抛出异常(提供的代码)

时间:2011-09-14 17:56:03

标签: c++ exception

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

2 个答案:

答案 0 :(得分:2)

getProductID不会抛出异常。你抓住了在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;
}

* - 要启用g++中的警告,-Wall是一个很好的起点。 @Tomalak Geret'kal建议-Wall -Wextra -std=c++98 -pedantic-Wall -Wextra -std=c++0x -pedantic

答案 1 :(得分:1)

try {
   throw myExcept_Prod_Not_Found;   
}
catch (exception& e) {
   cout<<e.what()<<endl;     
}  

在这里你抛出异常,然后立即抓住它。将异常消息输出到控制台,然后正常执行您的功能......除了您没有返回值。

因此,该函数调用的结果是未指定,并且您从内存中看到一些任意垃圾以及调用未定义的行为

相反,只是让异常通过不捕获它来传播callstack:它将导致程序终止(可能没有实际展开,顺便说一下):

throw myExcept_Prod_Not_Found;
相关问题