-4
#include <exception>
#include <iostream>

using namespace std;
class A
{
public:
    A(int n) : i(n) { cout << i; }

    ~A() { cout << i; }

private:
    int i;
};

int f(int n)
{
    if (n == 1) {
        throw std::logic_error("0");
        cout << "7" << endl;
    }
    A a(n);
    return f(n - 1);
}

int main() //main function
{
    try {
        int ret = f(3);
        A a(ret);
    }
    catch (const std::exception &e) {
        cout << e.what() << endl;
    }
    return 0;
}

Why the output of this c++ in exceptional handling is 32230 ? I am little bit confused.

I am using ATOM for programming Thanks

7

2 Answers 2

1

This is due to the order of your operations.

1) First, creation of A with n = 3 is called, so it prints 3.

2) Then, trhough f(n-1), creation of A with n = n-1 = 2 is called, it prints 2.

3) Then through f(n-1=1), throw 0 is called. It leaves the function f.

4) when leaving step 3), the programs leaves then the function f(2) called in step 2). So it destroy the object a created in step 2), it prints 2

5) When leaving step 4), the programs leaves then f(3) called in step 1). So it destroy the a created in step 1), it prints 3

6) It prints the error that was thrown: 0

You can see how all the steps are done either with a debugger and going step by step, or even following the algorithm on a paper..

0

You are calling function f recursive. This means first you create an object with 3, the constructor outputs 3, next recursion with 2, constructor outputs 2, next recursion 1, now you will run in the exception handler.

Exception raises back through the recursion so you get 2 from destructor in second recursion level and 3 from destructor 1 level. Finally, you output 0 with e.what().

Result 32230.

Not the answer you're looking for? Browse other questions tagged or ask your own question.