尝试/捕捉&不能正常工作

时间:2011-11-10 05:35:36

标签: c++ class templates linked-list try-catch

我似乎无法让我的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.
} 

1 个答案:

答案 0 :(得分:4)

你正在抛出一个字符串,但是试图抓住指向字符串的指针。

将您的try / catch块更改为:

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

你获得该中止消息的原因是因为你没有“抓住”与你所投掷的内容兼容的类型,所以异常就是绕过你的捕获,因此是一个“未捕获的异常”,受默认的底层异常处理程序控制,该处理程序调用abort。

FYI更标准的方法是抛出/捕获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.") );
相关问题