Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Throwing Exception If Popping Empty Queue

I'm writing an implementation of a priority queue using linked list nodes in C++.

I am new to the language and would really appreciate it if someone could help me figure out how to throw an exception when the pop() function is called on an empty queue.

I have tried using the try and catch exception handling but my code keeps getting a "segmenation fault error"

My priority queue is implemented correctly.. push(), isEmpty(), size(), clear() work. pop() also functions but I want to throw an exception if the user makes an illegal call.

try {
    if(isEmpty()) {
        throw -1;
    }
}
catch(int n) {
    cout << "ERROR" << n << ": LIST IS EMPTY" << endl;
}

1 Answers

You throw an exception with a throw statement. There's no try or catch involved. It's the responsibility of the caller to catch the exception.

if (isEmpty())
    throw -1;
like image 119
Pete Becker Avatar answered Sep 07 '26 03:09

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!