Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding 'try' : C++

Tags:

c++

exception

Consider below code:

#include <iostream>
#include <stdexcept>

class E{
    public:
        E(int n):m_n(n)
    {
        if (0>n)
        {
            throw std::logic_error("5");
        }
    }
        ~E(){cout << m_n << "#" <<endl;}
    public :
        int m_n;
};

int main()
{
    try{
        E a(5);
        try{
            E c(7);
            E b(-8);
            E d(9);
        }
        catch(const std::exception &e)
        {
            cout <<2 <<"&&&"<<e.what()<<endl;
            throw e;
        }
    }
    catch(const std::exception &e)
    {
        cout <<3 << "^^^^^ "<<e.what() << endl;
        throw e;
    }
    return 0;
} 

The output I got is:

7#
2&&&5
5#
3^^^^^ St9exception
std::exception: St9exception
Aborted.

Can some one please explain why such output? I expect first 5# to be displayed.

like image 385
Gaurav K Avatar asked Jun 06 '26 23:06

Gaurav K


1 Answers

Here's the workflow of your program in pseudocode:

{
  //outer try
  create e(5);
  {
    //inner try
    create e(7);
    failed create e(-8);//exception here
    throw;
    delete e(7);//-> 7#
  }
  {
    //catch in inner try;
    cout &&&;//-> 2&&&5
    throw e; // throw sliced copy of original exception
  }
  delete e(5);//-> 5#
}
{
  //catch in outer try
  cout ^^^^;//-> 3^^^^^ St9exception (the last thrown is pure std::exception)
  throw e; // throw another copy, no more slicing as it's already exception
}
program termination because of uncaught exception;
//-> std::exception: St9exception
//-> Aborted.

//return 0; was never reached
like image 67
SpongeBobFan Avatar answered Jun 09 '26 13:06

SpongeBobFan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!