C Exception Handling Sample Driver TrashCan yours TrashCan m
C++ Exception Handling
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;
}
Solution
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\");
}
mySize = size;
}
}
TrashCan (int size, int contents)
{
if(size < 0) {
throw logic_error( \"Constructor (size, content) : Size value is negative\");
}
else{
mySize = size;
}
if(contents < 0 ) {
throw logic_error( \"Constructor (size, content) :Content value is negative\");
}
else {
if (contents > size) {
throw logic_error( \"Constructor (size, content) :Content value exceeds Size value\");
}
else{
myContents = contents;
}
}
}
TrashCan operator+(const TrashCan& b){
TrashCan tc;
tc.mySize = this->mySize + b.mySize;
tc.myContents = this->myContents - b.myContents;
if(tc.myContents > tc.mySize){
throw logic_error( \"+ve Operator: Content size exceeds size value\" );
}
else{
return tc;
}
}
TrashCan operator-(const TrashCan& b){
TrashCan tc;
tc.mySize = this->mySize - b.mySize;
if(tc.mySize < 0){
throw logic_error( \"-ve Operator: size become negative after subtraction\" );
}
else
{
tc.myContents = this->myContents - b.myContents;
if(tc.myContents < 0){
throw logic_error( \"-ve Operator: Contents become negative after subtraction\" );
}
else{
return tc;
}
}
}
void setSize(int amount)
{
if (amount < 0 ){
throw logic_error( \"setSize: size become negative after subtraction\" );
}
else {
if(amount < myContents){
throw logic_error( \"setSize: Content size exceeds size value\" );
}
this->mySize = amount;
}
}


