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