c++gccthrowerrnogetlasterror

Does throwing an exception affect errno or set last error code


Supposing the Foo constructor does not call any function that affect errno or similar status codes like GetLastError() on Windows, is it guaranteed that

throw Foo

does not affect any of these values. That said, can I post-pone the read of error code until the constructor of Foo? If not specified by the standard, I am most interested in the behaviour of GCC, GNU/Linux and MinGW-SJLJ variants.


Solution

  • The function GetLastError() is Windows specific and non standard. Exceptions don't affect the value returned: only calls to OS function update it (unless you call SetLastError()).

    Nevertheless, throwing an exception has potential impacts on automatic objects that were in scope:

    15.2/1 As control passes from the point where an exception is thrown to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction.

    If the destructor of any such objects contains call to the OS, this might have an impact on GetLastError().

    To summarize: First the Foo constructor is called, then the destructors of already completely constructed local objects is called, and finally the throw "transfers controls" to the nearest exception handler. So no library function is expected to be called. The standard uses the same wording ("transfer control" or "pass control") for any elementary flow control statements, such as break, continue, and goto.