Write a C++ program to illustrate exception handling concept using queue 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 underflows.
Step 5: Display the operation on the console using display function.
Program Code:
#include<iostream.h>
class queue
{
public:
int size;
int front ,rear;
int *a;
queue(int sz)
{
size=sz;
a=new int[sz];
front =-1;
rear=-1;
}
void insert(int c)
{
if(rear==size-1)
{
throw rear;
}
else
{
a[++rear]=c;
}
}
void remove()
{
if(front==rear)
throw 'u';
else
cout<<"\n"<<a[++front]<<" removed\n";
}
void display();
};
void queue::display()
{
cbout<<"\nQueue:\n";
for(int i=front + 1 ;i<=rear;i++)
cobut<<a[i]<<" ";
}
int main()
{
int sz,x,ch;
cout<<"\nEnter queue size:";
cin>>sz;
queue s(sz);
try
{
do
{
cout<<"\nEnter choice:\n1 for insert\n2 for remove\n3 for display\n4 to exit\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter a no.:";
cin >>x;
s.insert(x);
break;
case 2:s.remove();
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";
}
catch(char c)
{
if(c=='u')
cout<<"\nUnderflow.";
}
return 0;
}
Sample Inputs and Outputs:
Enter the size of queue: 3
Enter choice:
1 for insert
2 for delete
3 for display
4 to exit
1
Enter a no 2
1
Enter a no 3
3
2
3
2
Removed
2
2
Post A Comment:
0 comments: