Windows核心编程笔记之错误处理

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_38924942/article/details/88621593

0x01 GetLastError() 函数用于获取上一个操作的错误代码

#include <Windows.h>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
	HANDLE nFile = CreateFile(TEXT("D:\\noknow.txt"), 0, 0, NULL, OPEN_EXISTING, 0, NULL);
	DWORD error =  GetLastError();
	cout << "错误代码: " << error << endl;
	return 0;
}

输出结果为
在这里插入图片描述

0x02 利用 VS 小工具查看

  • 利用 errlook.exe 工具查询错误代码 2 的含义
    在这里插入图片描述

0x03 错误代码转换为相应的文本描述

#include <Windows.h>
#include <iostream>
#include <strsafe.h>
using namespace std;

void ErrorExit(LPTSTR lpszFunction);

int main(int argc, char *argv[])
{
	WCHAR var_1[] = L"错误代码";
	ErrorExit(var_1);
	return 0;
}

void ErrorExit(LPTSTR lpszFunction)
{
	// 检索最后错误码的系统错误消息

	LPVOID lpMsgBuf; 
	LPVOID lpDisplayBuf;
	DWORD dw = 123;                      // 模拟错误代码定义为 123

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER | // 函数自动使用 LocalAlloc 函数,来为 lpBuffer 分配内存
		FORMAT_MESSAGE_FROM_SYSTEM |	 // 定义可以使用 GetLastError 的返回值赋给 dw 
		FORMAT_MESSAGE_IGNORE_INSERTS,   // 这个标志表示 Arguments 参数将被忽略
		NULL,							 // 消息所在位置,这个参数类型,根据dwFlags标志来设定
		dw,								 // 消息索引,如果 lpSource 是一个字符串,那么这个参数被忽略
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),  // 设置为本地默认语言
		(LPTSTR)&lpMsgBuf,				 // 接受消息字符串的内存块
		0,								 // 内存大小
		NULL);							 // 消息中的参数		

	// 显示错误消息并退出进程

	lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, // 将内存初始化为 0
		(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); // 为字符串指针区域申请足够大小的内存

	StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf),  // 目标缓冲区和目标缓冲区的大小
		TEXT("%s %d 的含义是: %s"),			 // 格式字符串
		lpszFunction,						 // 参数1
		dw,									 // 参数2
		lpMsgBuf);							 // 参数3

	MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

	LocalFree(lpMsgBuf);      // 释放空间
	LocalFree(lpDisplayBuf);
	ExitProcess(dw);		  // 关闭进程
}

输出的结果为,相当于 errlook.exe 小工具
在这里插入图片描述

设置自己的错误代码

#include <Windows.h>
#include <iostream>
using namespace std;

#define MY_ERROR 100L

void SetError(INT a);

int main(int argc, char *argv[])
{
	SetError(0);
	cout << GetLastError() << endl;
	return 0;
}

void SetError(INT a)
{
	if (a == 0) SetLastError(MY_ERROR);
}

输出结果为 100
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38924942/article/details/88621593