For a Class assignment i wrote a program that has to throw a logic_error and then catch it but my code doesn't work i don't know what am i doing wrong.

#include <iostream>
#include <iomanip>
#include <exception>
#include <stdexcept>
using namespace std;
std::logic_error;
struct MyException : public exception
{
  const char * what () const throw ()
  {
    return "CS50 Exception";
  }
};

int main()
{
  try
  {
    throw MyException();
  }
  catch(MyException& e)
  {
    std::cout << "MyException found" << std::endl;
    std::cout << e.what() << std::endl;
  }
  catch(std::exception& e)
};
void MyException;

TrashCan();
TrashCan( int size );
TrashCan( int size, int contents );
void setSize( intsize );
voidaddItem();

void empty( );
void cover( );
void uncover( );

void printCan( );

bool myIsCovered;
int my_Size;
int my_Contents;
cs52::TrashCan t;
cs52::TrashCan yourCan( 128 );
cs52::TrashCan junk( 12 );
t.setSize( 3 );
t.addItem();
t.addItem();
t.addItem();
t.cover();

/// how can you have negative number of items
/// TrashCan???
try {
junk = yourCan - t;
cout << junk; 
} catch( std::logic_error le ) {
cout << "subtraction failed" << endl;
}


/// how can a contents of 4 items in a TrashCan
/// which has only has size 3??/
try {
t.addItem( );
} catch( std::logic_error le ) {
cout << "addItem failed" << endl;
}

//// t should be unchanged
cout << t << endl;

/// how can you have TrashCans with a negative
/// size??
try {
TrashCan myCan( -19 ); 
} catch( std::logic_error le ) {
cout << "constructor failed!" << endl;
}

A way to throw and catch a logic_error exception:

int main(){
    try{
        throw logic_error("err");
    }
    catch(logic_error& e){
        cout<<e.what()<<endl;
    }
    return 0;
}

Also, have a look at the logic_error class from c++: Click Here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.