'Break on thrown exception only when...' in Xamarin Studio

A tool that's probably already made it into your debugging flow when using Xamarin Studio is the 'Exception Catchpoint' feature. It functions in a manner roughly equivalent to the 'Exceptions' debug window in Visual Studio. An exception catchpoint is actually just a special type of breakpoint that can be used to pause the debugger when an exception is thrown, rather then if - and only if - is unhandled. Breaking on thrown exceptions can often help you understand the true source of an error, which may be masked or represented differently by a libary or framework's code by the time it reaches the top of the call stack and becomes a dreaded unhandled exception.

One potential issue with breaking on thrown exceptions is that some of your libraries may be exceptionally (get it 🏄) chatty or liberal in their throwing and catching of exceptions. In these cases, as soon as you start breaking on exceptions at throw time, you'll also find your app pausing for many exceptions you don't care about.

Fortunately, it's possible to use Xamarin Studio's breakpoint editor dialog to filter out exceptions you dont want to stop for, or lock down to certain types of occurrences only. It's clear that you can break only for certain subclasses of Exception, but it's also possible to use the Advanced Conditions part of the dialog to specify a condition which will let you perform more involved checking. The dialog states that "scope of the statement is local to the breakpoint" - but where is the breakpoint when this is an exception catchpoint?

It turns out the breakpoint is wherever the exception occurred, which means the question then is - how can I access the exception itself? Checking the Locals pad at the time of the break reveals it all - you can access the thrown exception via the $exception variable, and perform all the additional checking you need. Here's an example:

In this case, we have two exceptions being thrown, but caught. These will not tear down the app, nor result in the debugger stopping under ordinary conditions. They are both of type Exception so if we want to stop for only one of them, we can use the advanced conditions to filter on the Message property. With the settings above, we'll break only for the first exception, not the second (or any others). Of course, if you wanted a 'blacklist' style approach, you could use a negating condition and get everything except those matching the condition.

This is one of those things that you probably won't need every day. Still, when you end up in a situation where you do need it, it's likely be a godsend. I'd always figured it would be possible somehow, but until triggered to check by a question from a fellow MVP, never looked properly investigated. I can already remember times when I could have used this, maybe you can too. In any case, just another tool in the belt this is your debugging arsenal.