Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break on unhandled exceptions in Silverlight

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?

like image 976
Bruno Martinez Avatar asked May 11 '10 21:05

Bruno Martinez


2 Answers

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.
        }
    }
}
like image 177
hemp Avatar answered Sep 28 '22 05:09

hemp


In your web project, make sure the debugging of Silverlight applications checkbox is checked. You'll find the setting under the web application's Properties->Web tab.

In VS2008, hit Ctrl+Alt+E to bring up the Exceptions window, check the box under the Thrown column for "Common Language Runtime Exceptions". In VS2010, I don't believe the shortcut works, so you'll need to go to the Debug->Exceptions from the dropdown menu.

I'm not sure if this is exactly what you're looking for, but hopefully it helps!

like image 34
Greg Levenhagen Avatar answered Sep 28 '22 04:09

Greg Levenhagen