Write a C++ program to illustrate exception handling concept using stack operation as an example.

Program Algorithm:
Step 1: Include the Header file.
Step 2: Create a class Stack which initializes size of the stack
Step 3: Create function push to do insert operation which in turn throws an exception when it overflow.
Step 4: Create function pop to do delete operation which in turn throws an exception when it underflow.
Step 5: Display the operation on the console using display function.

Program Code:
#include<iostream.h>
class Stack
{
public:
int size;
int top;
int *a;
Stack(int sz)
{
size=sz;
a=new int[sz];
top =-1;
}
void push(int c)
{
if(top==size-1)
{
throw top;
}
else
{
a[++top]=c;
}
}
void pop()
{
if(top==-1)
throw top;
else
cout<<"\n"<<a[top--]<<" removed\n";
}
void display();
};
void Stack::display()
{
cout<<"\nStack:\n";
for(int i=0 ;i<=top;i++)
cout<<a[i]<<" ";
}
int main()
{
int sz,x,ch;
cout<<"\nEnter stack size:";
cin>>sz;
Stack s(sz);
try
{
do
{
cout<<"\nEnter choice:\n1 for push\n2 for pop\n3 for display\n4 to exit\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter a no.:";
cin >>x;
s.push(x);
break;
case 2:s.pop();
break;
case 3:s.display();
break;
case 4:return 0;
break;
default:
cout<<"Enter a valid choice.";
}
}while(1);
}
catch(int a)
{
if(a==s.size-1)
cout<<"\nOverflow\n";
else
cout<<"\nUnderflow";
}
return 0;
}


Sample Inputs and Outputs:
Enter the size of stack: 3
Enter choice:
1 for push
2 for pop
3 for display
4 to exit
1
Enter a no 2
1
Enter a no 3
3
3
2
2
Removed
3
2
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: