Reputation: 153
In my program I want to catch every error in a function. I've tried using a try/catch but the program still exits. I've set up an example of what I want to catch
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<string> test;
test.push("lel");
try {
test.pop();
test.pop();
}
catch (...) {
cout << "Caught" << endl;
}
return 0;
}
This still causes the program to exit. How can I catch any error, or if it's not possible, this specific error?
Upvotes: 1
Views: 348
Reputation: 7625
stack::pop()
does not throw any exception
when the stack is empty. Rather it is undefined behavior to pop from an empty stack. Since no exception is thrown, your catch
clause can not catch anything, rather program terminates ( anything can happen in UB).
So about your intention of catching all error, I think it is good practice to put a try-catch
in main
to catch anything that escaped from any other place, and you should be able to catch if exception is actually being thrown. Just take care of some issues:
catch
block in case of any UB.Upvotes: 7
Reputation: 145204
The std::stack::pop
function is defined by C11++ §23.6.5.2 as
void pop() { c.pop_back(); }
Table 101 in C++11 §23.2.3/16 places the following requirement on a call to pop_pack
:
” Requires:
a.empty()
shall befalse
.
This means that the call to pop
on an empty stack breaks the function's contract, and therefore has Undefined Behavior.
There is no portable way to detect the effect, whatever it turns out to be for your C++ implementation and particular run of the program. But with a given C++ implementation it may be more clearly defined and there you may be able to catch it.
Upvotes: 1