GetLastError

Function

GetLastError

Syntax

DWORD GetLastError(void);

Parameters

This function does not take any parameters.

Return Value

The return value is the last error code set by a thread. If there is no error, the return value is ERROR_SUCCESS (0).

Remarks

Each thread maintains its own last-error code. A thread's last-error code is set when a function fails. It is not automatically cleared when a function succeeds. Therefore, after a function call that might fail, you should always call GetLastError immediately to retrieve the error code.

The last-error code is a per-thread value. Multiple threads can call functions that set the last-error code independently without interfering with each other.

If a function call succeeds, the return value is not necessarily zero. The last-error code is meaningless until a function fails. You should only call GetLastError when you need to retrieve the error code for a function that has returned failure.

Note: Do not assume that a return value of zero from a function always indicates success. Some functions return zero even on success. Always check the function's documentation for specific return value conventions.

Tip: For a comprehensive list of Windows error codes, refer to the Error Codes page.

Example

C++ Example

#include <windows.h>
#include <iostream>

int main() {
    // Attempt to open a non-existent file
    HANDLE fileHandle = CreateFile(
        L"C:\\path\\to\\non_existent_file.txt",
        GENERIC_READ,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );

    if (fileHandle == INVALID_HANDLE_VALUE) {
        DWORD error = GetLastError();
        std::cerr << "Error opening file. Error code: " << error << std::endl;

        // You can use FormatMessage to get a human-readable error string
        LPSTR messageBuffer = nullptr;
        size_t size = FormatMessageA(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            error,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPSTR)&messageBuffer,
            0,
            NULL
        );

        std::cerr << "Error message: " << messageBuffer << std::endl;

        LocalFree(messageBuffer);
    } else {
        std::cout << "File opened successfully." << std::endl;
        CloseHandle(fileHandle);
    }

    return 0;
}