11

For the following code

struct X
{
    int x;
    X() noexcept try : x(0)
    {
    } 
    catch(...)
    {
    }
};

Visual studio 14 CTP issues the warning

warning C4297: 'X::X': function assumed not to throw an exception but does

note: __declspec(nothrow), throw(), noexcept(true), or noexcept was specified on the function

Is this a misuse of noexcept? Or is it a bug in Microsoft compiler?

a.lasram
  • 4,371
  • 1
  • 16
  • 24

1 Answers1

12

Or is it a bug in Microsoft compiler?

Not quite.

A so-called function-try-block like this cannot prevent that an exception will get outside. Consider that the object is never fully constructed since the constructor can't finish execution. The catch-block has to throw something else or the current exception will be rethrown ([except.handle]/15):

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.

Therefore the compiler deduces that the constructor can indeed throw.

struct X
{
    int x;
    X() noexcept : x(0)
    {
        try
        {
            // Code that may actually throw
        }
        catch(...)
        {
        }
    } 
};

Should compile without a warning.

David G
  • 94,763
  • 41
  • 167
  • 253
Columbo
  • 60,038
  • 8
  • 155
  • 203