Program returns garbage value

I understand that since the value requested isn't found, there is no "id"
available for it, so the compiler just assigns it a garbage value. Now how do I throw the exception before the compiler gets a chance to assign the garbage value to the product id.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
myException.h
#ifndef _MY_EXCEPTION_H
#define _MY_EXCEPTION_H

#include <stdexcept>
#include <iostream>
#include <string>

using namespace std;

class Exception_ID_Not_Found: public exception {
	public:
		virtual const char* what() const throw() {
			return " not found";
		}
};

int getProductID(int ids[], string names[], int numProducts, string target);

#endif


myException.cpp
int getProductID(int ids[], string names[], int numProducts, string target) {
	Exception_ID_Not_Found notFound;

	try {
		for (int i = 0; i < numProducts; i++) {
			if (names[i] == target)
				return ids[i];
		}
		throw(notFound);
	} catch (exception &e) {
		cerr << target << e.what() << endl;
	}
}

#include <iostream>
#include <exception>
#include <string>
//#include <new>
#include "myException.h"

using namespace std;

int main() // Sample code to test the getProductID function
{
	int productIds[]= {4, 5, 8, 10, 13};
	string products[] = { "computer", "flash drive", "mouse", "printer", "camera" };

	cout << getProductID(productIds, products, 5, "mouse") << endl;
	cout << getProductID(productIds, products, 5, "camera") << endl;
	cout << getProductID(productIds, products, 5, "laptop") << endl;

	return 0;
}
Perhaps the question you want to ask doesn't really have to do with exceptions at all, if you use a std::vector instead of an array you can get the size() of the list instead of passing in the numProducts variable, then you can simply return your error code when you go out of bounds on your array.

However if you are set on exceptions, that is your prerogative.

In this specific case can you help us understand what seems to be happening? Is someone passing in a bad value for numProducts, do you have a misalignment of ids and names causing one of them to return a bad value? What seems to be the issue?

Also if you want a product id for a particular string please look into std::map which allows you to directly associate pairs of two values, which can be a string and an int value.
Last edited on
Topic archived. No new replies allowed.