开发者

The sample code provided returns a random number, even after throwing an exception (code provided)

开发者 https://www.devze.com 2023-04-04 17:23 出处:网络
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

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 <iostr开发者_运维技巧eam>
#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 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.

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;
}

* — 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.


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

Here you're throwing an exception and then immediately catching it. The exception message is output to console and then execution of your function continues as normal... except you have no value to return.

So, the result of that function call is unspecified, and you're seeing some arbitrary rubbish from memory as well as invoking undefined behaviour.

Instead, just let the exception propogate right up the callstack by not catching it: it'll lead your program to terminate (possibly without actually unrolling, incidentally):

throw myExcept_Prod_Not_Found;
0

精彩评论

暂无评论...
验证码 换一张
取 消