理解'try':C++

Gau*_*v K 3 c++ exception-handling

考虑以下代码:

#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;
} 
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

7#
2&&&5
5#
3^^^^^ St9exception
std::exception: St9exception
Aborted.
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么这样的输出?我希望首先显示5#.

Spo*_*Fan 5

这是您的程序在伪代码中的工作流程:

{
  //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
Run Code Online (Sandbox Code Playgroud)