Programming

C++ Program to Queue/Exception Implementation in C++

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

Source code

#include<iostream>

#include<conio.h>

using namespace std;

#define max 2

class queue

{

    int front,rear;

    int n[max];

    public:

    queue()

    {

    front=0;

    rear=-1;

    }

    void enqueue()

    {

    if(rear==max-1)

    throw "Overflow";

    else

    {

    int x;

    cout<<"\n Enter a number:";

    cin>>x;

    n[++rear]=x;

    cout<<x<<" is enqueued!\n";

    }

    }

void dequeue()

    {

    if(front>rear)

    throw "Underflow!";

    else

    cout<<n[front++]<<" is dequeued!\n";

    }

    };

    int main()

    {

    queue q1;

    int ch;

    try

    {

    do

    {

    cout<<endl<<"1.Enqueue 2.Dequeue 3.Exit Enter choice:";

    cin>>ch;

    switch(ch)

    {

    case 1:

    {

    q1.enqueue();

    break;

    }

    case 2:

    {

    q1.dequeue();

    break;

    }

    }

    }

    while(ch!=3) ;

    }

    catch(char *msg)

    {

    cout<<msg<<endl;

    }

    getch();

}

Output

queue management

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.