我正在尝试为一段C ++代码引发异常,因此它将通过测试。得到以下代码:
YourClass::YourClass()
:timeIter{timepoints}
{
}
然后提示我:
我们现在可以使用CustomStackException类创建自定义异常。例如,我们可以测试堆栈何时已满或为空:
void StackTest::testPop() {
cout << "- Testing pop()... " << flush;
// try empty, capacity 1
Stack s1(1);
assert( s1.isEmpty() );
try {
s1.peekTop();
cerr << "\npeekTop() worked on empty stack (size 1)\n";
exit(1);
} catch (CustomStackException& se) {
cout << " 0a " << flush;
}
try {
s1.pop();
cerr << "\npop() worked on empty stack (size 1)\n";
exit(1);
} catch (CustomStackException& se) {
cout << " 0b " << flush;
}
...
这是我尝试过的。测试现在完成并给出结果,但是我不确定是否正确执行了此操作,因为我没有在示例代码中包括stackFunction部分。有人可以解释示例代码的各个部分吗?
stackFunction() {
if ( isFull() ) {
throw CustomStackException("stackFunction()", "stack is full");
} else {
return variable;
}
}
...
正确抛出异常后,它将导致测试通过。
当前结果:
void StackTest::testPop() {
cout << "- Testing pop()... " << flush;
// try empty, capacity 1
Stack s1(1);
assert( s1.isEmpty() );
try {
s1.peekTop();
cerr << "\npeekTop() worked on empty stack (size 1)\n";
//FIXME: 3. Throwing an exception if s1.isFull
if( s1.isFull() ){
throw CustomStackException("peekTop()", "stack is full");
}else{
return;
}
exit(1);
} catch (CustomStackException& se) {
cout << " 0a " << flush;
}
try {
s1.pop();
cerr << "\npop() worked on empty stack (size 1)\n";
//FIXME: 3. Throwing an exception if s1.isFull
if( s1.isFull() ){
throw CustomStackException("pop()", "stack is full");
}else{
return;
}
exit(1);
} catch (CustomStackException& se) {
cout << " 0b " << flush;
}