gpt4 book ai didi

c++ - 如何从 CloseHandle() 捕获异常

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:49 26 4
gpt4 key购买 nike

根据 MSDN 规范,CloseHandle 在调试器下运行时,如果传递给它的句柄无效,则会引发异常。

因为我想要干净的代码,所以我插入了一些代码来捕捉它。但是,它不起作用,异常未被捕获。

#include <windows.h>
#include <tchar.h>
#include <exception>
/* omitted code */
CloseHandle(myHandle); // close the handle, the handle is now invalid
try {
success = CloseHandle(myHandle);
} catch (std::exception& e) {
_tprintf(TEXT("%s\n"), e.what());
} catch (...) {
_tprintf(TEXT("UNKNOWN\n"));
}

我从调试器中得到以下两个错误:

First-chance exception: 0xC0000008: An invalid handle was specified.

Uncaught exception: 0xC0000008: An invalid handle was specified.

我认为第一次异常是正常的,因为它在 catch 语句应该得到它之前就被触发了。但是,未捕获的异常让我想知道这里到底出了什么问题。

最佳答案

你有两个选择:

选项 1:
使用SEH,需要这样写:

__try
{
// closeHandle
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
// print
}

选项 2:
使用编译器开关/EHa,它将指示编译器发出代码,允许您通过 C++ 样式的异常处理来处理 SEH 异常:

try
{
// close handle
}
catch (...)
{
// print
}

编辑:
请注意,CloseHandle() 只会在调试器附加到您的进程时引发异常。来自文档:

If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value.

关于c++ - 如何从 CloseHandle() 捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1550315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com