Reputation:
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;
}
Upvotes: 3
Views: 5503
Reputation: 7092
Throwing an integer as an exception really isn't the done thing in c++. You really should create either a new exception for the job or pick one of the existing exceptions std library that might fit situation.
Yes the domain says java, but it's a c++ tutorial and has an example of how to create a custom exception derived from std::runtime_error.
Upvotes: 1
Reputation: 76315
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;
Upvotes: 1