GetLastError

Overview

The GetLastError function retrieves the last error code set by a thread. The error code is a system-defined value that can represent any error that occurs during the execution of a function.

Syntax

DWORD GetLastError();

This function takes no parameters.

Parameters

This function does not take any parameters.

Return Value

The return value is the last error code set by the calling thread. If there is no error, the return value is 0.

For a complete list of error codes, see System Error Codes.

Remarks

Each thread maintains its own last-error code. A thread's last-error code is set whenever any function called by that thread fails. Some functions set the last-error code even when they succeed. Always check the return value of a function to determine if it failed before calling GetLastError to retrieve the error code.

The ERROR_SUCCESS (0) value is returned if the function succeeded. If the function returns FALSE and GetLastError returns ERROR_SUCCESS, it usually means that the function did not successfully complete its operation.

To map a last-error code to a formatted string that describes the error, use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag.

Examples

The following example demonstrates how to use GetLastError to retrieve the error code after a failed file operation.

// Attempt to open a non-existent file
HANDLE hFile = CreateFile(
    "non_existent_file.txt",
    GENERIC_READ,
    0,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL
);

if (hFile == INVALID_HANDLE_VALUE) {
    DWORD dwError = GetLastError();
    // Handle the error, for example, by logging or displaying a message
    printf("Failed to open file. Error code: %lu\n", dwError);
} else {
    // File opened successfully
    CloseHandle(hFile);
}

See Also