A compact version of your code makes the bug obvious:
if (hProcess != NULL)
{
// Left out for brevity
}
else
{
// Here, hProcess is NULL
CloseHandle(hProcess);
SystemErrorMessage();
}
In essence, this is calling CloseHandle(NULL);
, presumably setting the thread's last error code to ERROR_INVALID_HANDLE
. SystemErrorMessage()
probably blindly calls GetLastError
(without evaluating whether it should), and throws an exception if the value returned is anything other than ERROR_SUCCESS
.
To fix this, you need to fix the logic bug (remove the call to CloseHandle
in the else
branch, in which you know hProcess
to be invalid). When done, rework your entire error handling. It won't work reliably. You cannot blindly call GetLastError, anytime an API call failed. When done with that, study the RAII idiom, so that you won't have to write manual cleanup code, like you would have to do with C.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…