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?
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.本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句