Bill Blogs in C#

Bill Wagner discusses C#, LINQ, and other items of interest

Why do exceptions you can't see stop your program in the debugger
A reader asked why the VS.NET debugger sometimes stops execution of your program for an exception that you don't create. The debugger sees exceptions generated in the framework too.

I received this question via email recently, and I thought the answer would be of general interest:

We are currently working through a book study on the Effective C# book and I have come across an "issue" I was hoping you could help me understand....it is funny since I spent a number of hours working through this EXACT issue in my application, and then I went home that night to ready the chapters for the book study and you described the exact issue.  Unfortunately the example code is showing the same problem as my application.

This sample piece of code below will throw a "First Chance Exception" (in the IDE with all exceptions turned on under the Debug/Exceptions menu) if the file does NOT exist....I can NOT catch the exception in a try/catch block AND the code continues to execute normally after that (and the file is even created!!)....kinda weird.  I took this code "directly" from Item 47

 static void Main(string[] args)
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForDomain();
  // This next line causes a "first chance exception" if the file does NOT exist,
//
but then it creates the file anyways..
  IsolatedStorageFileStream myStream =
new IsolatedStorageFileStream("FredTest.txt", FileMode.Create, iso);
}

Here’s my answer: 

The IsolatedStorageFileStream constructor generates and catches the exception when the file does not exist.

That’s why you see it in the debugger, when “stop on all exceptions” is set. The framework does catch the exception, and creates the missing file system resources. That’s why the code runs correctly, even though it does generate the exceptions. That’s why I usually try to run the IDE where it only stops on exceptions that are uncaught, rather than all exceptions. At times, stopping on all exceptions is just not practical. NUnit is another example: it generates a number of exceptions when it loads, but it catches them all.

(For those of you following along at home (using Reflector or ILDASM), examine IsolatedStorageFile.Init() for the particular try / catch block involved in this example.)



Published Tuesday, February 22, 2005 5:31 AM by wwagner
Filed under:

Comments

No Comments