In Windows programming, the GetLastError() function retrieves the error code from the most recent failed API call. If a Windows API function fails, you can immediately call GetLastError() to obtain the specific error code. Understanding error codes is essential for debugging and error handling.
To obtain a human-readable error message from the error code returned by GetLastError(), you can use the FormatMessage() function. This function looks up the corresponding descriptive text based on the error code, helping developers understand the cause of the error.
Steps
- Call the API function: First, you need to call a Windows API function.
- Check for errors: If the function returns an error indication (typically NULL or FALSE), you should immediately call
GetLastError()to retrieve the error code. - Call
FormatMessage(): Use the obtained error code to call theFormatMessage()function to get the descriptive text message.
Example Code
cpp#include <windows.h> #include <iostream> int main() { // Simulate an error scenario, such as opening a non-existent file HANDLE hFile = CreateFile(TEXT("nonexistent.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); LPVOID lpMsgBuf; // Use FormatMessage to get the error information FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); // Display the error message std::wcout << L"Error code: " << dwError << L"\nError message: " << (LPCTSTR)lpMsgBuf << std::endl; // Free memory LocalFree(lpMsgBuf); } return 0; }
In this example, we attempt to open a non-existent file, which causes the CreateFile function to fail. When the function fails, we retrieve the error code using GetLastError() and obtain and display the error message using FormatMessage().
By doing this, you can obtain specific error information based on the error code, which is very helpful for debugging and error handling.