When many system functions fail, they set the last-error code. If your application needs more details about an error, it can retrieve the last-error code using the GetLastError function and display a description of the error using the FormatMessage function.
The following example includes an error-handling function that prints the error message and terminates the process. The lpszFunction parameter is the name of the function that set the last-error code.
#include <windows.h>
#include <strsafe.h>
void ErrorExit(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
void main()
{
// Generate an error
if(!GetProcessId(NULL))
ErrorExit(TEXT("GetProcessId"));
}
'VisualStudio.C++.C# > 코딩팁,함수활용,단편' 카테고리의 다른 글
다른 프로그램과 메시지 송수신. - RegisterWindowMessage (0) | 2015.06.05 |
---|---|
Virtual-Key Codes. VC++ (0) | 2015.01.19 |
키보드 입력처리. VC++ MFC 이용하는 경우. (0) | 2015.01.19 |
동적 메모리 할당. 변수,배열, new delete (0) | 2015.01.17 |
스레드 생성 방법 및 다중스레드 사용위한 필수 옵션 셋팅. VC++ (0) | 2015.01.10 |
댓글