我似乎无法使try / catch正常工作。当您实现try / catch时,应该“抛出”您告诉它的任何字符串,对吗?如果需要,请让程序继续。我的没有说我想要说的话,也没有继续,而是告诉我这然后中止了:

调试错误!等等等等
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.") );

10-06 13:27
查看更多