2011-11-10 97 views
0

我似乎無法讓我的try/catch正常工作。當你實現一個try/catch時,它應該「拋出」你告訴它的任何字符串,對吧?如果你想,讓程序繼續。那麼我的不會說我想說的話,也不會繼續,相反它告訴我,然後中止:Try/Catch&Throw not working properly

調試錯誤! Blah blah blah.exe R6010 -abort()已被調用(按重試以調試應用程序)

我想讓它說:「您正在嘗試添加超出允許的數量的項目。然後繼續執行該程序。這是一個LinkedList,它不能讓它有超過30個節點。當它試圖添加超過30個時,它會停止,而不是我想要的。我不確定我做錯了什麼,非常感謝!

Main: 
    Collection<int> list; 

    for(int count=0; count < 31; count++) 
    {  
     try 
     { 
      list.addItem(count); 
      cout << count << endl; 
     } 
     catch(string *exceptionString) 
     { 
      cout << exceptionString; 
      cout << "Error"; 
     } 
    } 
    cout << "End of Program.\n"; 

Collection.h: 
template<class T> 
void Collection<T>::addItem(T num) 
{ 
    ListNode<T> *newNode; 
    ListNode<T> *nodePtr; 
    ListNode<T> *previousNode = NULL; 

    const std::string throwStr = "You are trying to add more Items than are allowed. Don't. "; 

    // If Collection has 30 Items, add no more. 
    if(size == 30) 
    { 
     throw(throwStr); 
    } 
    else 
    {}// Do nothing.    

    // Allocate a new node and store num there. 
    newNode = new ListNode<T>; 
    newNode->item = num; 
    ++size; 

    // Rest of code for making new nodes/inserting in proper order 
    // Placing position, etc etc. 
} 

回答

4

你正在拋出一個字符串,但試圖捕獲一個指向字符串的指針。

更改您的try/catch塊這樣的:

try 
{ 
... 
} 
catch(const string& exceptionString) 
{ 
    cout << exceptionString; 
} 

你得到中止消息的原因是因爲你沒有「惡補」一類是與你扔東西兼容,所以這個異常只是繞過你的catch,因此是一個「未捕獲的異常」,受限於默認的底層異常處理程序,它調用中止。

僅供參考一個更標準的方法是拋出/捕獲一個std :: exception對象。即

try 
{ 
... 
} 
catch(std::exception& e) 
{ 
    std::cout << e.what(); 
} 


... 

throw(std::logic_error("You are trying to add more Items than are allowed. Don't.")); 
+0

這樣做的竅門!非常感謝你! :) – Riotson