C ++新手。奇怪的平地机试图捕获异常???如何安抚平地机?

时间:2018-06-30 05:16:08

标签: c++ exception-handling

我正在做一些暑期练习,并且陷入了这一挑战。目的是创建一个简单的setItem()函数。如果testSetItem()函数无例外地运行,则质询已通过。

这是代码。了解如何引发range_error异常以安抚测试功能。

我提交时,评分员说:

  

libc ++ abi.dylib:终止于类型为std :: range_error:helpme的未捕获异常

我的尝试:

void Vec::setItem(unsigned index, const Item &it) {
    if(index==0 || index > mySize)
        throw std::range_error("helpme");
    myArray[index] = it;
}

平地机代码:

void VecTester::testSetItem() const {
    cout << "Testing setItem()... " << flush;
    // empty case
    Vec v0;
    try {
        v0.setItem(0, 11);
        cerr << "setItem() succeeded on empty Vec";
        exit(1);
    } catch (range_error&) {       <--------HOW DO I APPEASE THIS???
        cout << " 0 " << flush;
    }
    // nonempty case, valid subscript
    Vec v(5);
    for (unsigned i = 0; i < 5; i++) {
        v.setItem(i, i+1);
    }
    for (unsigned i = 0; i < 5; i++) {
        assert( v.myArray[i] == (i+1) );
    }
    cout << " 1 " << flush;
    // nonempty case, invalid subscript
    Vec v2(3);
    try {
        v2.setItem(3, 33);
        cerr << "setItem() succeeded beyond end of Vec";
        exit(1);
    } catch (range_error&) {
        cout << " 2 " << flush;
    }
    cout << "Passed!" << endl;
}

0 个答案:

没有答案