Using $exception within Visual Studio’s Debugger

Here is a little tip that I discovered today. Quite often you will develop exception handling code that looks like the following:

try {
  // do something here which may fail
catch (FileNotFoundException) {
  // do some error handling here which
  // doesn't refer to the exception object
  // that has been thrown
catch (Exception) {
  // do some more generic error handling here

Since our exception handling code makes no use of the exception object that has been thrown, we do not need to declare a variable to reference it (i.e. the traditional “ex”). However this leads to an issue while debugging. Without a variable there is nothing to mouse over in order to display the exception’s contents once the initial popup has been dismissed.

Up until today I would typically modify the code to look like the following:

try {
  // ...
catch (FileNotFoundException ex)
  // ...

This allows me to mouse over the variable ‘ex’ in order to view the contents of the exception. However this meant that I needed to modify the source code and restart the debugging session (hoping I could re-create the error condition). It also meant that a compile time warning (”CS0168: The variable ‘ex’ is declared but never used.”) was produced, since the compiler correctly points out that I am not using this variable.

What I learnt today was that instead of doing this you can add the special variable $exception to the debugger’s Watch Window, or query it via the Immediate Window. This variable references the currently thrown exception when located within a catch block.

Screenshot of Visual Studio 2005 IDE showing the Watch Window display the value of the $exception variable

Now for the bad news, unfortunately this tip only seems to work for applications targeting the full Desktop framework, when developing a Smart Device or .NET Micro Framework project the watch window reports “The name ‘$exception’ does not exist in the current context”.

One Response to “Using $exception within Visual Studio’s Debugger”

  1. Mauro Chojrin says:


    I’m working on a project related to application development under Windows CE. I have downloaded the code for the google-gears-ce and I was wondering if you could help me with some compilation problems I’ve been having. I would be very grateful if you could reply this post. Thanks.

Leave a Reply