I am using mingw g++ 4.6.1 with -O0, WinXP SP2.
Minimal working example is here.
g++ is configured with –disable-sjlj-exceptions –with-dwarf2.
GetLastError() returns 0 or 2 depeding on how the exception is thrown:
throw runtime_error(error_message());
bogus “error code: 0” is printed, and
const string msg = error_message();
throw runtime_error(msg);
prints “error code: 2” as expected.
First, I thought GetLastError() is invoked twice but debugging shows it is invoked exactly once, as expected.
What is going on?
It’s possible that the code that sets up a
throwcalls a Win32 API function inside itself somewhere, that resets the Last-Error value to 0. This may be happening before your call toerror_message().Calling
GetLastError()does not automatically reset the Last-Error value to 0, so it is safe to call twice.Whether your compiler/runtime generates code that calls a Win32 API function will be up to your specific runtime. In order to be safe and not depend on this, use the two-statement version:
Better yet, for future readers of your code it would be useful to call
GetLastError()outsideerror_message():This way, readers will see the
GetLastError()call immediately after the corresponding Win32 API call, where it belongs.