7

I'm having trouble for a while with error C2712: Cannot use __try in functions that require object unwinding, after narrowing the problem, I was left with a very very simple code, and i can not understand why it causes this error. I am using Visual Studio under windows.

I am compiling with /EHa (I do not use /EHsc)

The reason I use __try/__except and not try/catch is because I want to catch ALL the errors, and do not want the program to crash under any circumstances, including for example division by 0, that try-catch does not catch.

#include <string>
static struct myStruct
{
    static std::string foo() {return "abc";}
};

int main ()
{
    myStruct::foo();

    __try 
    { }
    __except (true)
    { }

    return 0;
}

output:

error C2712: Cannot use __try in functions that require object unwinding
15
  • You are probably misguided in this desire to catch all exceptions. Anyway, to make this work, I think you need to move the __try/__catch blocks to a different function.
    – Praetorian
    Jul 15, 2014 at 0:57
  • @Praetorian i did that, and it works, but all my main is full with static functions, and i want the try-except to be over all the main Jul 15, 2014 at 1:00
  • What if you move everything within main() into another function (do_main), and then do __try { do_main(); } ...?
    – Praetorian
    Jul 15, 2014 at 1:02
  • It might work, but what is the problem in this example? Why is it not working? Jul 15, 2014 at 1:03
  • 1
    The error message is pretty clear. The string object returned by myStruct::foo() requires stack unwinding for destruction, and catching SEH exceptions is not supported in such functions.
    – Praetorian
    Jul 15, 2014 at 1:05

1 Answer 1

7

Here is the solution. For more details read Compiler Error C2712

#include <string>
struct myStruct
{
    static std::string foo() {return "abc";}
};

void koo()
{
    __try 
    { }
    __except (true)
    { }
}

int main ()
{
    myStruct::foo();   
    koo();
    return 0;
}

Extra Note: no need static if no declaration using your struct (myStruct).

1
  • What you're doing doesn't make sense as you don't protect your code with __try/__except.
    – KeyC0de
    Jan 14, 2021 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.