How to catch exception from CloseHandle()
Solution 1
You have two options:
Option 1:
Use SEH, you need to write something like this:
__try
{
// closeHandle
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
// print
}
Option 2:
Use the compiler switch /EHa, which will instruct the compiler to emmit code which will allow you to handle SEH exception via C++ style exception handling:
try
{
// close handle
}
catch (...)
{
// print
}
Edit:
Note that CloseHandle()
only raises an exception if a debugger is attached to your process.
From the documentation:
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.
Solution 2
I guess MSDN is talking about SEH exceptions, which are not the same as C++ exceptions.
Comments
-
Etan almost 2 years
As of the MSDN spec,
CloseHandle
throws an Exception if an invalid handle is passed to it when it runs under a debugger.Since I want to have clean code, I've inserted some code to catch it. However, it doesn't work, the exception gets uncaught.
#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")); }
I get the following two errors from the debugger:
First-chance exception: 0xC0000008: An invalid handle was specified.
Uncaught exception: 0xC0000008: An invalid handle was specified.
I think that the first-chance exception is normal, since it gets fired before the catch statement should get it. However, the uncaught exception makes me wondering what's actually wrong here.
-
Etan over 14 yearsthanks! What is the way to go for to get the text "An invalid handle was specified."? 0xC0000008 can be gotten via GetExceptionCode()
-
Pierre Bourdon over 14 yearsYou may try the FormatMessage function, but I'm not sure about that one : msdn.microsoft.com/en-us/library/ms679351(VS.85).aspx
-
user720594 almost 12 yearsIf it still throws this exception, even if you have __try/__except, you probably have enabled breaking on this exception. Go to menu Debug/Exceptions/Win32 Exceptions and disable option c0000008 An invalid handle was specified. After OK breaking to Visual Studio should stop.