问题
#include <exception>
struct FOO
{
~FOO() try
{
throw std::exception();
}
catch (...)
{
return; // Shall prevent the exception from being rethrown?
}
};
Building this code in Visual Studio triggers C4297 warning (function assumed not to throw an exception but does).
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;
Do I interpret this sentence correctly? Does return from the catch statement shall prevent the exception from being rethrown?
I logged a bug but they closed it as duplicate. The other bug does not have a return statement
but I think it makes all the difference.
Live example
回答1:
Do I interpret this sentence correctly? Does return from the catch statement shall prevent the exception from being rethrown?
I believe you are. For one, it is explicitly stated that in a constructor, the handler of a function-try-block may not include a return statement.
[except.handle]
13 If a return statement appears in a handler of the function-try-block of a constructor, the program is ill-formed.
The only way to explicitly leave such a handler is by throwing another exception. A return statement is disallowed precisely for the reason that it will swallow the exception. When we leave a handler implicitly, by flowing of the end
14 The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. Otherwise, flowing off the end of the compound-statement of a handler of a function-try-block is equivalent to flowing off the end of the compound-statement of that function (see [stmt.return]).
The bit in [stmt.return] says that reaching the closing brace of a void returning function is equivalent to a return;
at the end. So the first sentence tells us that in a handler of a destructor's function-try-block, flowing of the end is not a return;
, it rethrows. There is no implicit return there.
This leaves only the conclusion that explicitly returning, by virtue of not being prohibited, must swallow the current exception.
来源:https://stackoverflow.com/questions/63176146/c4297-warning-in-visual-studio-while-using-function-try-block-function-assumed