简体   繁体   中英

Throw exception from invalid parameter handler

I'm using VS2015 and I want to throw errno from invalid parameter handler so that I can format error message in catch block. My code looks like this:

_set_invalid_parameter_handler([](wchar_t const*, wchar_t const*, wchar_t const*, unsigned int, uintptr_t) {
    throw errno;
});
try
{
    char buffer[2];
    strcpy_s(buffer, "testtest");
}
catch (int e)
{
    //strerror
    perror("catch int");
}
catch (...)
{
    perror("catch ...");
}

If I compile in debug mode, the code works fine while in release mode it crashed. Why it behaves differently?

You must change a compile option, the optimizer removes exception filters too aggressively in the Release build so your program bombs through terminate() right now.

Ensure you have the Release configuration selected, Project > Properties > C/C++ > Code Generation > Enable C++ Exception setting. Change it from the default of /Ehsc to /Ehs.

The "c" qualifier it the sting here, it allows the optimizer to assume that an extern "C" function can never throw a C++ exception. strcpy_s() is a C function. Using /Eha fixes it as well, that forces the optimizer to assume nothing at all. But makes catch (...) too dangerous, it will now also catch the really nasty SEH stuff like AV.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM