C++ Exception Handling Program Sample Driver: TrashCan yours; TrashCan mine; Tra
ID: 3774853 • Letter: C
Question
C++ Exception Handling Program
Sample Driver:
TrashCan yours;
TrashCan mine;
TrashCan test;
yours.setSize( 10 );
mine.setSize( 10 );
test.setSize( 5 );
yours.addItem( );
mine.addItem( );
mine.addItem( );
mine.addItem( );
mine.addItem( );
mine.addItem( );
test.addItem( );
test.addItem( );
test.addItem( );
test.addItem( );
test.addItem( );
cout << test << endl;
try {
// contents will become negative...
// an exception should get thrown
test = yours - mine;
} catch( std::logic_error le ) {
cout << "subtraction failed" << endl;
}
/// test should be unchanged
cout << test << endl;
try {
// how can you have a negative size
// an exception should get thrown
test = TrashCan( -100 );
} catch( std::logic_error le ) {
cout << "constructor failed" << endl;
}
/// test should be unchanged
cout << test << endl;
try {
// how can you have 5 pieces of
// trash in a can that
// can only hold 3??
// an exception should get thrown
test.setSize( 3 );
} catch( std::logic_error le ) {
cout << "setSize failed" << endl;
}
/// test should be unchanged
cout << test << endl;
try {
// how can you have a negative
// contents value??
test = TrashCan( 10, -100 );
} catch( std::logic_error le ) {
cout << "constructor failed" << endl;
}
Explanation / Answer
#include <iostream>
#include "TrashCan.h"
using namespace std;
int main( ) {
// Let's use the TrashCan
cout << "Welcome to Howie's Trash-R-Us." << endl;
cout << "Reuse, Reduce, Recycle!" << endl;
TrashCan t;
t.setSize( 10 );
t.addItem();
t.cover();
t.printCan();
return( 0 );
}
TrashCan yours( 5, 3 );
TrashCan mine( 100, 3 );
yours.addItem( );
mine.addItem( );
cout << "----some tests follow----" << endl;
TrashCan eightItems = mine + mine;
TrashCan zeroItems = yours - yours;
eightItems.printCan();
zeroItems.printCan();
if (eightItems > zeroItems) {
cout << "> is working..." << endl;
}
if (eightItems != zeroItems) {
cout << "!= is working..." << endl;
}
if (zeroItems < eightItems) {
cout << "< is working..." << endl;
}
if (eightItems == eightItems) {
cout << "== is working..." << endl;
}
cout << "---some broken code follows---";
// each of the operator calls below should print out
// some kind of error message, instead of working correctly...
TrashCan negativeItems = mine - eightItems;
TrashCan overfull = yours + yours;
Follwoing is requried code
TrashCan (int size)
{
if(size < 0)
{
throw logic_error( "Constructor (size) :Size value is negative");
}
else
{
if (myContents > size)
{
throw logic_error( "Constructor (size) :myContents value exceeds size value");
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.