views:

111

answers:

2

What is the difference between the WINAPI SetLastError() and the C++ keyword throw? For example, are SetLastError(5); and throw 5; the same?

+4  A: 

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.

AshleysBrain
+8  A: 

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