Error Handling Functions

The Win32 API provides a set of functions and mechanisms for handling errors that occur during program execution. Understanding these is crucial for writing robust and reliable Windows applications.

GetLastError()

Retrieves the last error code set by a thread.

Parameters:
  • None.
Return Value: The return value is the last error code, which is a system-defined value that can be greater than or equal to 0x00000000 and less than or equal to 0x000000FF. If the function succeeds, the return value is zero. If the function fails, the return value is the data from the last error.
Remarks:

Call this function immediately after a function call that might fail. The error code is stored on a per-thread basis. A return value of 0 indicates success. However, some functions set the last-error code to 0 even on failure. Therefore, to distinguish between failure and success, you must check the return value of the function that failed.

The system error codes are defined in WinError.h and are listed in the Windows SDK documentation.

FormatMessage()

Formats a message string.

DWORD FormatMessage(
  DWORD   dwFlags,
  LPCVOID lpSource,
  DWORD   dwMessageId,
  DWORD   dwLanguageId,
  LPSTR   lpBuffer,
  DWORD   nSize,
  va_list *Arguments
);
Parameters:
  • dwFlags: The source and formatting options.
  • lpSource: Specifies the source of the formatted message.
  • dwMessageId: The message identifier.
  • dwLanguageId: The language identifier.
  • lpBuffer: The buffer that receives the formatted message.
  • nSize: The maximum size of the buffer.
  • Arguments: Values used to fill parameterized error values.
Return Value: If the function succeeds, the return value is the number of characters stored in the buffer, not including the terminating null character. If the function fails, the return value is zero.
Remarks:

This function is invaluable for converting raw error codes into human-readable error messages.

Common Error Codes

While the list is extensive, some common error codes encountered include: