Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing '__try' and 'try' in single function - Through Lambda

It is known that Windows SEH doesn't go along with C++ exception handling mechanism. We cannot use try and __try in single function. This will lead to compiler error:

__try
{
   try
   {
       MayThrowCPPException_OR_SEH();
   }
   catch(...)
   {
   }
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}

It will render:

C2713: Only one form of exception handling permitted per function.

One option, which most people don't like is "Yes with SEH Exceptions (/EHa)" compiler option. This will facilitate C++ try/catch to handle both of the exception. We need to put such function in separate file, and put /EHa only for that source file.

Another option is to put try (or __try) in one function, and have another function which will have __try( or try).

Question Begins While trying to do the above, I tried by just having a C++ lambda to fool the compiler. Here is what I did:

auto call_this =[] 
{
   MayThrowCPPException_OR_SEH();
   // C++ exception handling here.
};
__try
{
   call_this();
}
__except(...)
{
}

And this compiled fine on VC++ 2013 update 5.

Is it safe to do so?

like image 634
Ajay Avatar asked Oct 31 '22 21:10

Ajay


1 Answers

Yes, this is safe. The lambda body is just an operator() method of an unnamed lambda type. This method has the C++ exception handler. The outer function has the SEH handler.

like image 122
MSalters Avatar answered Nov 09 '22 12:11

MSalters