Developing for Windows Phone is a lot of fun, but there are some times, where it's a bit frustrating.

From time to time, you'll find that your app exiting for no apparent reason. There are no exceptions raised, either in the emulator or a real device.

For most of the exceptions, like navigation or XAML parsing exceptions, you can use the Debug / Exceptions dialog (given that you use the "Just my code" feature wisely) and break the execution at the proper location.

But there is a kind of exception that will not be caught by the exception handling : The StackOverflowException.

If you run this nice piece of code :

public int Test(int i, int j, int k)
{
    return Test(i + 1, i + 1, i + 1);
}

Well guess what, your application will exit without any notice, and it won't seem like an unhandled exception.

This particular example is simple, but if you got a large codebase, or that the StackOverflow is in a separate thread, finding the culprit can be pretty difficult in the dark...

 

Debugging a StackOverflowException

 

So how is it possible to debug that kind of exception ? Well, there are a few options like guessing with the use of Debug.WriteLine or putting some breakpoints at various places to find which part of the code causes the stack overflow.

But the Windows Phone 7.1 SDK comes with a nice tool : The Performance Profiler !

The tool has features to analyze the performance of the application by doing stack sampling, visual tree analysis, GPU and Compositor thread analysis, Thread context breakdown, and many more.

But for this particular issue, getting a sense of what's been executed can be pretty useful.

So if we run the previous piece of code using the profiler, this is what we get :

Pretty interesting read. It becomes clear that the "Test" is the problem.

You may also want to run the profiler on the a real device, as a full blown I7 is filling the stack in less than 10ms... And don't let it run too long as well, as the profiler will not like it very much, and you might crash visual studio :)