C++ Programming

C++ Create Class Stack and Add Exception (PUSH, POP, TRAVERSE)

Create the class stack and add the exception when user tries to add items while the stack is full and when user tries to delete item while the stack is empty. Throw exception in both the cases and handle these exception.

Source Code

#include<iostream>

#include<conio.h>

#include<process.h>

#include<ctype.h>

using namespace std;

class stack1

{

protected:

int stac[10],item,tos;

public:

stack1()

{

tos=-1;

}

void push()

{

cout<<"\nEnter data to be inserted: ";

cin>>item;

tos++;

stac[tos]=item;

cout<<"Data inserted: "<<item;

}

void pop()

{

cout<<"\nThe data popped is "<<stac[tos];

tos--;

}

void traverse()

{

int i=0;

cout<<"\nThe items in the stack are: ";

for(i=0;i<=tos;i++)

cout<<"\t"<<stac[i];

}

};

class stack2:public stack1

{

public:

void input()

{

if(tos>=5)

throw"\n***Exception: STACK FULL ***\n ";

else

push();

}

void output()

{

if(tos==-1)

throw"\n***Exception: STACK EMPTY ***\n ";

else

pop();

}

void display()

{

if(tos==-1)

throw"\n***Exception: STACK EMPTY ***\n copyright ";

else

traverse();

}

};

int main()

{

stack2 obj;

int c;

cout<<"\n\n1. PUSH  2. POP  3. TRAVERSE  4. EXIT\n ";

do{

cout<<" \n\nENTER THE CHOICE: ";

cin>>c;

switch(c)

{

case 1:

    try{

    obj.stack2::input();

    }

    catch(char *msg)

    {

    cout<<msg<<endl;

    }

    break;

    case 2:

    try{

    obj.stack2::output();

    }

    catch(char *msg)

    {

    cout<<msg<<endl;

    }

break;

    case 3:

    try{

    obj.stack2::display();

}

    catch(char *msg)

{

    cout<<msg<<endl;

}

    break;

    case 4:

    exit(0);

    default:

    cout<<"\n*** INVALID ***";

    }

    }while(getch());

    getch();

}

Output

Back to top button