[英]Try/Catch & Throw not working properly
我似乎無法使try / catch正常工作。 當您實現try / catch時,應該“拋出”您告訴它的任何字符串,對嗎? 如果需要,請讓程序繼續。 我的沒有說我想說的話,也沒有繼續,而是告訴我這然后中止了:
調試錯誤! 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.
}
您正在拋出一個字符串,但是試圖捕獲一個指向字符串的指針。
將您的try / catch塊更改為:
try
{
...
}
catch( const string& exceptionString )
{
cout << exceptionString;
}
之所以收到該異常中止消息,是因為您沒有“捕獲”與您所拋出的異常兼容的類型,因此該異常只是繞過了捕獲,因此是“未捕獲的異常”,受制於默認的基礎異常處理程序,它調用中止。
僅供參考,更標准的方法是拋出/捕獲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.") );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.