gpt4 book ai didi

c++ - 如果我不 catch 会怎样?

转载 作者:IT老高 更新时间:2023-10-28 21:54:33 24 4
gpt4 key购买 nike

这是 super 基本的,但我无法在任何地方找到答案。有很多关于 throw 和捕捉的帖子,但是如果我从 function1 throw 然后从 function2 调用 function1 会发生什么 但不捕获它,这是否意味着它只是被重新抛出给 function2 的调用者?从以下内容来看,我会说是的,但我想在我坚持下去之前得到一个可靠的大师般的答案并假设:

#include <iostream>

void function1()
{
throw 1;
}

void function2()
{
function1();
}

int main()
{
try
{
function2();
}
catch(...)
{
std::cout << "caught!";
return 0;
}
return 0;
}

输出:
抓到了!

最佳答案

是的,这就是异常的工作方式。当异常被抛出时,它会被调用堆栈中的最顶层函数捕获,该函数在执行范围内具有该异常的处理程序。由于您要返回堆栈中较低的函数,因此较高堆栈帧中函数范围内的某些变量需要超出范围,因此会调用它们的析构函数。这称为堆栈展开。将它与 RAII 结合起来真是太好了(如果您不知道那是什么,请查找 RAII)。但是,如果任何析构函数在堆栈展开期间抛出异常,那么它是坏的并且将调用 std::terminate 函数。通常你的程序会结束(这就是为什么总是建议你编写非抛出的析构函数)。

来自 cppreference.com :

Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of a try block, at which point the parameters of the associated catch blocks are compared with the thrown expression to find a match. If no match is found, the control flow continues to unwind the stack until the next try block, and so on. If a match is found, the control flow jumps to the matching catch block (the exception handler), which executes normally.

As the control flow moves up the call stack, destructors are invoked for all objects with automatic storage duration constructed since the corresponding try-block was entered, in reverse order of construction. If an exception is thrown from a constructor, destructors are called for all fully-constructed non-static non-variant members and base classes. This process is called stack unwinding.

关于c++ - 如果我不 catch 会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19429360/

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