Program:- Description:-
#include <iostream> Changes Made:
#include <conio.h> Changed void main() to int main().
using namespace std;
Changed Try to try.
int main() // starting of main function
{ Included necessary headers (<iostream> and
int FirstValue, SecondValue; // declaring two <conio.h>).
variables of int type
cout << "Enter values of FirstValue and Used _getch() instead of system("pause") to make
SecondValue\n"; the program pause and wait for a key press.
cin >> FirstValue >> SecondValue; // taking 2
int values from the user Updated the output message in the catch block to
int ConditionVariable; clarify the thrown value.
ConditionVariable = FirstValue >
SecondValue ? 0 : 1; // checking whether 1st Explanation:
entered value is greater than 2nd or not
main should return an int and should return 0 at
try // starting of try block the end.
{
if (ConditionVariable == 0) try should be in lowercase.
{
cout << "Subtraction (FirstValue - _getch() is used to wait for a key press, which is a
SecondValue) = " << FirstValue - SecondValue << part of the
"\n"; <conio.h> library, making it work similarly to
} system("pause")
else but more portable within Windows environments.
{
throw(ConditionVariable); // throwing
exception if ConditionVariable is not equal to zero
}
} // end of try block
catch (int thrownValue) // start of catch block
{
cout << "Exception caught:
ConditionVariable = " << thrownValue << endl; //
displaying thrown value
} // end of catch block
cout << endl << endl;
_getch(); // waits for a key press
return 0;
}
Task #1
Output:-
Task#2
Program:- Desceiption:-
#include <iostream>
#include <stdexcept> Explanation
using namespace std; Custom Exception Class: The
// Custom exception class NegativeNumberException class inherits from
class NegativeNumberException : public
runtime_error { std::runtime_error. It has a constructor that
public:
NegativeNumberException() : initializes the base class with an error message.
runtime_error("Negative number encountered")
{} AbsoluteNumber Class: This class contains:
};
A private member variable value to store the
// Class for handling absolute numbers number.
class AbsoluteNumber {
private: A constructor that initializes value using the
int value; setValue method.
public: A setValue method that checks if the provided
// Constructor value is negative. If it is, it throws a
AbsoluteNumber(int val) {
setValue(val); NegativeNumberException.
}
A getValue method that returns the current value.
// Setter main Function: In the main function:
void setValue(int val) {
if (val < 0) { An AbsoluteNumber object is created with a
throw NegativeNumberException(); positive value.
}
value = val; The value is printed.
}
The value is set to another positive value and
// Getter printed again.
int getValue() const {
return value; When attempting to set a negative value, the
} NegativeNumberException is thrown, caught, and
};
an error message is displayed.
int main() { Usage
try {
AbsoluteNumber num(5); When you run this program, it will:
cout << "Absolute number: " <<
num.getValue() << endl; Successfully create an AbsoluteNumber object
with the initial positive value.
cout << "Setting value to 10" << endl;
num.setValue(10); Update the value to another positive number.
cout << "Absolute number: " <<
num.getValue() << endl; Throw and catch an exception when trying to set a
negative value,
cout << "Setting value to -3" << endl;
num.setValue(-3); // This will throw an displaying the appropriate error message.
exception
}
catch (const NegativeNumberException& e) {
cerr << "Exception caught: " << e.what() <<
endl;
}
return 0;
}
Output:-
Task#3
Program:- Description:-
#include <iostream> Custom Exception Class
#include <stdexcept> (NegativeNumberException):
#include <string>
using namespace std; Inherits from runtime_error to leverage standard
exception handling.
// Custom exception class with error code and
message Contains private members errorCode and
class NegativeNumberException : public errorMessage to store the error code and message
runtime_error { respectively.
private:
int errorCode; The constructor initializes both errorCode and
string errorMessage; errorMessage.
public: getErrorCode method returns the error code.
NegativeNumberException(int code, const what method, overridden from runtime_error,
string& message)
: runtime_error(message), errorCode(code), returns the error message as a C-string using
errorMessage(message) {} c_str().
int getErrorCode() const { AbsoluteNumber Class:
return errorCode;
} Contains a private member value to store the
absolute number.
const char* what() const noexcept override {
return errorMessage.c_str();
}
}; Constructor that initializes the number using the
setValue method.
// Class for handling absolute numbers
class AbsoluteNumber { setValue method throws
private:
int value; NegativeNumberException with an error code and
a detailed message if a negative value is provided.
public:
// Constructor getValue method returns the current value.
AbsoluteNumber(int val) { main Function:
setValue(val);
} Creates an AbsoluteNumber object with an initial
positive value.
// Setter
void setValue(int val) { Updates the value to another positive number and
if (val < 0) { prints it.
throw NegativeNumberException(1001,
"Negative number encountered"); Attempts to set a negative value, which throws an
} exception.
value = val;
} Catches the NegativeNumberException and
displays the error message and error code.
// Getter Usage
int getValue() const {
return value; When you run this program:
}
}; It will successfully create an AbsoluteNumber
object with the initial positive value.
int main() {
try { Update the value to another positive number and
AbsoluteNumber num(5); display it.
cout << "Absolute number: " <<
num.getValue() << endl; Throw and catch an exception when trying to set a
negative value, displaying the appropriate error
cout << "Setting value to 10" << endl; message and error code.
num.setValue(10);
cout << "Absolute number: " <<
num.getValue() << endl;
cout << "Setting value to -3" << endl;
num.setValue(-3); // This will throw an
exception
}
catch (const NegativeNumberException& e) {
cerr << "Exception caught: Error Code " <<
e.getErrorCode()
<< ", Message: " << e.what() << endl;
}
return 0;
}
Home Task:-
Program:- Description:-
#include <iostream> Explanation
#include <stdexcept>
1. Exception Classes:
using namespace std; o QueueFullException and
QueueEmptyException inherit
class QueueFullException : public runtime_error from runtime_error and are used
{ to signal specific queue errors.
public: 2. Queue Class:
QueueFullException() : runtime_error("Queue o Members: The queue uses an
is full") {} array queue to store elements.
};
front and rear indices track the
class QueueEmptyException : public current front and rear of the
runtime_error { queue, and capacity is the
public: maximum size of the queue.
QueueEmptyException() : o Constructor: Initializes the
runtime_error("Queue is empty") {} queue with a given size and
}; sets the front and rear indices.
o Destructor: Deletes the
class Queue { allocated array.
private: o isEmpty: Checks if the queue
int front;
is empty.
int rear;
o isFull: Checks if the queue is
int capacity;
int* queue; full.
o enqueue: Adds an element to
public: the rear of the queue and
// Constructor to create a new, empty queue throws QueueFullException if the
object with a given capacity queue is full.
Queue(int size) : front(0), rear(-1),
o dequeue: Removes and returns
capacity(size) {
queue = new int[capacity]; the element at the front of the
} queue and throws
QueueEmptyException if the
// Destructor to clean up the allocated memory queue is empty.
~Queue() { o display: Prints the current
delete[] queue; contents of the queue.
} 3. main Function:
o Demonstrates the usage of the
// Check if the queue is empty Queue class, including
bool isEmpty() const {
enqueueing, dequeueing, and
return front > rear;
} exception handling.
o Attempts to perform
// Check if the queue is full operations on the queue,
bool isFull() const { handling exceptions as they
return rear == capacity - 1; occur.
}
// Insert an element at the rear of the queue
void enqueue(int element) {
if (isFull()) {
throw QueueFullException();
}
queue[++rear] = element;
}
// Remove and return the element at the front of
the queue
int dequeue() {
if (isEmpty()) {
throw QueueEmptyException();
}
return queue[front++];
}
// Display the queue contents
void display() const {
if (isEmpty()) {
cout << "Queue is empty" << endl;
} else {
cout << "Queue contents: ";
for (int i = front; i <= rear; ++i) {
cout << queue[i] << " ";
}
cout << endl;
}
}
};
int main() {
try {
Queue q(5);
// Enqueue elements
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
// Display the queue
q.display();
// Dequeue elements
cout << "Dequeued: " << q.dequeue() <<
endl;
cout << "Dequeued: " << q.dequeue() <<
endl;
// Display the queue again
q.display();
// Enqueue more elements
q.enqueue(60);
q.enqueue(70);
// Display the queue again
q.display();
// Attempt to dequeue all elements
while (!q.isEmpty()) {
cout << "Dequeued: " << q.dequeue() <<
endl;
}
// Try to dequeue from an empty queue
cout << "Attempting to dequeue from empty
queue:" << endl;
q.dequeue();
} catch (const QueueFullException& e) {
cerr << "Exception: " << e.what() << endl;
} catch (const QueueEmptyException& e) {
cerr << "Exception: " << e.what() << endl;
}
return 0;
}
Output:-
Conclusion:-
The provided code demonstrates a robust implementation of a queue data structure
in C++ with exception handling. The `Queue` class uses an array-based approach
to manage elements, ensuring that objects are enqueued at the rear and dequeued
from the front, adhering to the First-In-First-Out (FIFO) principle. Custom
exceptions, `QueueFullException` and `QueueEmptyException`, are defined to
handle scenarios where the queue is full or empty, respectively. The `Queue` class
includes essential methods for checking if the queue is empty or full, inserting
elements, and removing elements, along with a method to display the current
contents of the queue. The `main` function demonstrates the usage of these
methods, showcasing the correct handling of queue operations and exception
management. This implementation ensures that edge cases, such as attempting to
enqueue elements in a full queue or dequeue elements from an empty queue, are
managed gracefully with appropriate error messages.