gpt4 book ai didi

c++ - catch 是否保证在抛出异常后执行?

转载 作者:行者123 更新时间:2023-11-30 04:15:08 24 4
gpt4 key购买 nike

在维基百科中 we read :

Resource Acquisition Is Initialization RAII is a programming idiom used in several object-oriented languages like C++, D, Ada and Vala. The technique was invented by Bjarne Stroustrup to deal with resource allocation and deallocation in C++. In this language, the only code that can be guaranteed to be executed after an exception is thrown are the destructors of objects residing on the stack.

无论如何,我不想过于迂腐,但我真的不确定如何解释这一点。这是口误还是正确的? catch 处理程序不能保证至少被执行吗?

我知道 RAII 以及它是什么,我在这里重点关注这个唯一可以保证执行的代码 (..) 是驻留在堆栈上的对象的析构函数

最佳答案

严格来说,引用已经错了。当抛出异常并且没有匹配的处理程序时,可以调用 terminate 而无需展开堆栈和调用任何析构函数。因此,“析构函数保证在抛出异常时执行”的说法是错误的。

至于catch 处理程序本身,当然,只有当匹配的catch 处理程序存在 时,才有可能执行catch 处理程序。

最重要的是,即使处理程序存在,也有其他原因可以在工作中抛出 Spanner 并在异常到达 catch 处理程序之前过早地终止异常处理。例如,它发生在抛出“意外”异常时。如果您的函数异常规范禁止某些特定的异常类型,并且此类“禁止”类型的异常试图“飞出”该函数,则 unexpected 将立即被调用,而不是将控制权转移到处理程序。

如评论中所述,另一种典型情况是在由先前异常触发的堆栈展开期间抛出新异常。这将导致 terminate 被调用。

关于c++ - catch 是否保证在抛出异常后执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536593/

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