开发者

GetLastError called in a catch block yields incorrect value

Fun exploring some legacy code today. Ran into this little number:

function Func1()
{
DWORD dwError;
try
{
    dwError = 1;
    throw "Hey!";
} catch (LPCTSTR szError)
{
    Log("Log1: %d", dwError);
    SetLastError(dwError);
    throw szError;
}
}

f开发者_高级运维unction Func2()
{
    try {
       Func1();
    } 
    catch (LPCTSTR szError)
    {
         DWORD dwLastError = GetLastError();
         Log("Log2: %d", dwLastError); ///OMG is 0!
    }
}

GetLastError() returns 0! Why is that? The functions are actually a bit more complicated than this. They do include a few things on the stack (DWORDs, CString, BYTE[]). What should I be looking for?

Logs look like:

Log1: 1

Log2: 0


C++ exceptions in the MSVC compiler and runtime are built on top of native Windows SEH. Stack unwinding is actually performed by Windows. Using Windows api functions is going to affect the value stored for GetLastError(). More details about the connection with SEH in this answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜