gpt4 book ai didi

c++ - 理解 'try' : C++

转载 作者:太空狗 更新时间:2023-10-29 20:42:55 27 4
gpt4 key购买 nike

考虑下面的代码:

#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;
}

我得到的输出是:

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

有人可以解释为什么这样的输出吗?我希望显示第一个 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

关于c++ - 理解 'try' : C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340865/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com