user3103398
user3103398

Reputation: 153

Catching all errors

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

Answers (2)

Rakib
Rakib

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 mainto 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:

  1. Control may not reach in your catch block in case of any UB.
  2. C++ can not handle more than one exceptions simultaneously, in that case program will most likely terminate in place where it happens (specially be careful so that exception does not leave any destructor).
  3. Throwing exception that is not in exception specification list of a function (most likely program will terminate).

Upvotes: 7

Cheers and hth. - Alf
Cheers and hth. - Alf

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 be false.

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

Related Questions