How to execute GetLastError() while debugging in Visual Studio

Visual StudioDebuggingWinapi

Visual Studio Problem Overview


You're stepping through C/C++ code and have just called a Win32 API that has failed (typically by returning some unhelpful generic error code, like 0). Your code doesn't make a subsequent GetLastError() call whose return value you could inspect for further error information.

How can you get the error value without recompiling and reproducing the failure? Entering "GetLastError()" in the Watch window doesn't work ("syntax error").

Visual Studio Solutions


Solution 1 - Visual Studio

As mentioned a couple times, the @err pseudo-register will show the last error value, and @err,hr will show the error as a string (if it can).

According to Andy Pennell, a member of the Visual Studio team, starting with VS 7 (Visual Studio .NET 2002), using the '@' character to indicate pseudo-registers is deprecated - they prefer to use '$' (as in $err,hr). Both $ and @ are supported for the time being.

You can also use the $err pseudo-register in a conditional breakpoint; so you can break on a line of code only if the last error is non-zero. This can be a very handy trick.

Some other pseudo registers that you may find handy (from John Robbins' outstanding book, "Debugging Applications for Microsoft .NET and Microsoft Windows"):

  • $tib - shows the thread information block
  • $clk - shows a clock count (useful for timing functions). To more easily use this, place a $clk watch then an additional $clk=0 watch. The second watch will clear the pseudo register after the display of the current value, so the next step or step over you do gives you the time for that action only. Note that this is a rough timing that includes a fair bit of debugger overhead, but it can still be very useful.

Solution 2 - Visual Studio

ERR,hr in a watch window usually does the trick

Solution 3 - Visual Studio

"edit and continue" add the code so you can see the error (just don't create a new global variable to store it). It works really well if you can quickly put a call to a pre-existing function that executes this kind of error handling code.

As a bonus, you can leave the new code there for the future too.

If you can't do this, then QBziZ is right "ERR,hr" does it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter BaerView Question on Stackoverflow
Solution 1 - Visual StudioMichael BurrView Answer on Stackoverflow
Solution 2 - Visual StudioQBziZView Answer on Stackoverflow
Solution 3 - Visual StudiogbjbaanbView Answer on Stackoverflow