Reputation: 41
I'm not too familiar with exception handling so could someone help me with this problem?? So for this program, incase of a non-existing key in the std::map, I want to throw something but I dont know what.
the map key if it exists will be a phone number (string), but if it doesn't exist what would it be??
class SmartCarrier{
private:
string carrier_name_;
map<string,vector<Message*>> accounts_map;
public:
Search();
}
void phone::Search{
string phone_number;
map<string,vector<Message*>>::iterator iter;
cout << "Enter a phone number: ";
getline(cin,phone_number);
try{
iter = phone_map.find(phone_number);
if (iter ==phone_map.end()) {
//Incase of a non-existing phone number what do I throw?
throw iter;
}
}
catch(/*iter ??? what should the block catch as a value?*/){
cout << "Phone number not found." << endl;
}
Upvotes: 0
Views: 678
Reputation: 6440
I'd say that in this particular situation you don't need to throw any exceptions. The Search
name of the function, from the reader standpoint, probably means that the only responsibility of the function is to check whether or not there's a such element in the map. Returning value by an exception is a very strange (and inefficient) way. Here I would use std::map::count
- it returns 1
if such value is in the map, and 0
otherwise.
If you really need to throw an exception in case of abscence of value, look at std::map::at()
. It throws an std::out_of_range
exception if the key is not present.
For more info on std::map::at()
and other methods of retrieval information from std::map
please see this.
Upvotes: 0
Reputation: 4493
Rule of thumb - you always throw a derived class of std::exception
, if not stated otherwise by some style guide. You can use already defined common exceptions, like std::runtime_error
. And pass error data as exception argument, that's the whole point of exceptions - propagate the error data.
And always catch by const-reference.
In your case you might simply do:
try {
auto iter = phone_map.find(phone_number);
if (iter == phone_map.end()) {
throw std::runtime_error{ "Incorrect phone number" };
}
} catch(const std::exception& e){
cout << e.what() << endl;
}
In your case you can throw an iterator, and catch like this:
try {
throw phone_map.end();
} catch (const map<string,vector<Message*>>::iterator& e) {
// Do Something
}
But this is not recommended.
Upvotes: 1