.net – How to break on unhandled exceptions in Silverlight

.netexception-handlingsilverlight

In console .Net applications, the debugger breaks at the point of the throw (before stack unwinding) for exceptions with no matching catch block. It seems that Silverlight runs all user code inside a try catch, so the debugger never breaks. Instead, Application.UnhandledException is raised, but after catching the exception and unwinding the stack. To break when unhandled exceptions are thrown and not catched, I have to enable first chance exception breaks, which also stops the program for handled exceptions.

Is there a way to remove the Silverlight try block, so that exceptions get directly to the debugger?

Best Solution

This is fairly easy, actually.

Making use of the Application_UnhandledException event you can programmatically inject a breakpoint.
 

using System.IO; // FileNotFoundException
using System.Windows; // Application, StartupEventArgs, ApplicationUnhandledExceptionEventArgs

namespace SilverlightApplication
{
    public partial class App : Application
    {
        public App()
        {
            this.Startup += this.Application_Startup;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new Page();
        }

        private void Application_UnhandledException(object sender, 
            ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Break in the debugger
                System.Diagnostics.Debugger.Break();

                // Recover from the error
                e.Handled = true;
                return;
            }

            // Allow the Silverlight plug-in to detect and process the exception.
        }
    }
}