8
#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
  • Does that quote have a typo? It seems hard to believe that a destructor automatically rethrows when every article by every expert I've ever read says that destructors should never, ever throw under any circumstance. In fact the example code above the quote shows an implicit throw from a constructor, not a destructor.
    – shawn1874
    May 26, 2022 at 22:33

1 Answer 1

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.