very simple code, and getting error C2712, could not understand why

user1438233 picture user1438233 · Jul 15, 2014 · Viewed 9.3k times · Source

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

Answer

Nayana Adassuriya picture Nayana Adassuriya · Jul 15, 2014

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).