WINAPI SetLastError versus C++ Keword Throw
What is the difference between the WINAPI SetLastError()
and the C++ keyword throw
? For example, are SetLastError(5);
and thr开发者_如何学编程ow 5;
the same?
SetLastError sets a simple global variable, it does nothing to the flow of the program.
throw would stop the flow of the running program, unwind the stack until it is caught somewhere with a try - catch clause. The program flow would then continue from the end of the catch.
I suggest reading this article, which explains the concept of exceptions. And read up on C++ exceptions.
- Also, don't throw 5, throw an non-built in object, preferably inherited by std::exception. An object can contain some state telling the catch clause what to do with the error.
throw
throws an exception that is caught by a catch
block and is part of the C++ language. SetLastError()
is part of the Windows-specific API by Microsoft that changes the value returned by GetLastError()
. In other words, they're completely different! Throwing an exception unwinds the stack (calls destructors for all local variables) and moves program execution to the appropriate catch block. SetLastError()
does nothing like that, it's just an API function.
精彩评论