Having the following code with try-catch blocks and throwing exceptions, what will be displayed in the console?
#include <iostream>
using namespace std;

class Parent {
protected: 
    int _x;
public:
    Parent(int xx) : _x(xx) { cout << "P()"; }
    void setx(int x) { _x = x; }
    int getx() { return _x; }
};

class Kid : public Parent {
public:
    Kid(int xx) : Parent(xx) { cout << "K()"; }
};


int main()
{
    try
    {
        try
        {
            throw(Kid(3));
        }
        catch(Parent ob)
        {
            ob.setx(15);
            throw;
        }
        catch(Kid ob)
        {
            ob.setx(30);
            throw;
        }
    }
    catch(Kid ob)
    {
        cout << ob.getx();
    }
    return 0;
}
Explanation
In the first throw(Kid (3)) object of type Kid is created, therefore, P()K() will appear on the screen. This throw is caught in the catch(Parent ob), but the catching is done by the value of the object, i.e., a copy of Kid(3) is created, so the line ob.setx(15); will not change the original object created by Kid(3). Then exception is thrown up: (throw;) passing implicitly object Kid(3). This exception is caught (in the bottom) catch(Kid ob) and the value of the _x = 3 is displayed. Thus the result will be P()K()3

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes