gpt4 book ai didi

c++ - 使用function-try-block时在Visual Studio中发出C4297警告(假定函数不会引发异常,但会引发异常)

转载 作者:行者123 更新时间:2023-12-01 14:24:59 25 4
gpt4 key购买 nike

#include <exception>

struct FOO
{
~FOO() try
{
throw std::exception();
}
catch (...)
{
return; // Shall prevent the exception from being rethrown?
}
};
在Visual Studio中构建此代码会触发C4297警告(假定函数不会引发异常,但会引发异常)。

Reaching the end of a catch clause for a function-try-block on a destructor also automatically rethrows the current exception as if by throw;, but a return statement is allowed. quoted from cppreference.com;


我能正确解释这句话吗?从catch语句返回是否可以防止异常被重新抛出?
我记录了一个 bug,但他们将其关闭为 duplicate。另一个错误没有 return statement,但我认为它与众不同。
Live example

最佳答案

Do I interpret this sentence correctly? Does return from the catch statement shall prevent the exception from being rethrown?


我相信你是。首先,明确指出在构造函数中,函数try-block的处理程序可能不包含return语句。

[except.handle]

13 If a return statement appears in a handler of thefunction-try-block of a constructor, the program is ill-formed.


显式离开此类处理程序的唯一方法是引发另一个异常。确切地说,不允许使用return语句是因为它将吞噬异常。当我们隐式地离开处理程序时,

14 The currently handled exception is rethrown if control reachesthe end of a handler of the function-try-block of a constructor ordestructor. Otherwise, flowing off the end of the compound-statementof a handler of a function-try-block is equivalent to flowing off theend of the compound-statement of that function (see [stmt.return]).


[stmt.return] 中的位表示到达void返回函数的右括号等于最后的 return;。因此,第一句话告诉我们,在析构函数的function-try-block的处理程序中,结尾的流动不是 return;,而是重新抛出。那里没有隐式的返回。
这仅得出一个结论,即由于没有被禁止,显式返回必须吞下当前异常。

关于c++ - 使用function-try-block时在Visual Studio中发出C4297警告(假定函数不会引发异常,但会引发异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63176146/

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