我不太熟悉異常處理,所以有人可以幫我解決這個問題嗎?所以對於這個程序,在std :: map中存在一個不存在的鍵,我想拋出一些東西,但我不知道是什麼。異常處理。如何拋出一個迭代器?
映射鍵如果存在將是一個電話號碼(字符串),但如果它不存在,它會是什麼?
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;
}
'iter'的類型是什麼?這就是你需要抓住的。不是說你的情況真的很重要,因爲它總是等於'phone_map.end()'。我建議你使用[標準異常類之一](http://en.cppreference.com/w/cpp/error),可能是基於標準類自己編寫的。 –
同樣供您參考:如果不引發任何異常,使用異常對性能的影響可以忽略不計,但如果拋出並捕獲異常,則C++中的異常確實會對性能產生相當大的影響。例外情況只應用於*特殊*情況。未能驗證用戶輸入通常不是這種特殊情況。 –
我認爲這是異常處理的一個壞例子。你根本不需要try-catch塊。 –