Visual Studio (managed) debugger feature: magical local called $exception

One of the things you may have noticed when using the Visual Studio debugger (at least since 2005, if not sooner) is that if you have VS set to break on a CLR exception being thrown:

image

Then you get an extremely useful addition to your debug window Locals called $exception.  It’s not an actual local variable, of course, but a special addition from the VS debugger that lets you inspect and interact with the ‘active’ exception as if it were indeed a local variable:

Imagine we had this (broken) code as a console app:

Code Snippet
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4.  
  5. class Program
  6. {
  7.     static void Main(string[] args)
  8.     {
  9.         var path = args.FirstOrDefault();
  10.         var fullPath = Path.GetFullPath(path);
  11.         Console.WriteLine(fullPath);
  12.     }
  13. }

If we “run to cursor” (Ctrl+F10 by default) to the GetFullPath line, we get this at that point in time for our locals:

image

image

Now if you hit F5 (to run) or F10 (to step over) an exception gets thrown from that framework method and now we get a new entry in our Locals window called $exception:

image

NOTE: this special local is on the ‘first chance’ exception.  If you hit F10 to get it to a ‘second chance’ exception, you lose that special local and you’re back to a ‘normal’ exception (if you didn’t have break on exception thrown, this is what you would get to start with)

image

Advertisements

One thought on “Visual Studio (managed) debugger feature: magical local called $exception

  1. Pingback: Visual Studio debugger request: $return local variable « James Manning's Blog

Comments are closed.