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.
- None.
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.
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
);
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.
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:
ERROR_SUCCESS(0): The operation completed successfully.ERROR_INVALID_FUNCTION(1): Incorrect function.ERROR_FILE_NOT_FOUND(2): The system cannot find the file specified.ERROR_PATH_NOT_FOUND(3): The system cannot find the path specified.ERROR_ACCESS_DENIED(5): Access is denied.ERROR_INVALID_HANDLE(6): The handle is invalid.ERROR_NOT_ENOUGH_MEMORY(8): Not enough memory available to complete this operation.ERROR_INVALID_PARAMETER(87): The parameter is incorrect.