Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function-try-block and noexcept

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?

like image 712
a.lasram Avatar asked Oct 08 '14 22:10

a.lasram


1 Answers

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.

like image 103
Columbo Avatar answered Sep 22 '22 02:09

Columbo