Zebrastian
Zebrastian

Reputation: 481

Unable to handle unhandled exceptions in Xamarin Forms

I need to handle any unhandled exception in my Xamarin Forms Android app. I read that I can catch them in event handlers added in OnCreate in the MainActivity like so:

protected override void OnCreate(Bundle savedInstanceState)
{
    ...
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args)
{
    Exception e = (Exception)args.ExceptionObject;
    System.Diagnostics.Debug.WriteLine(e.Message);
}

I cause an exception from my MainPage:

public MainPage()
{
    InitializeComponent();
    Exception_Btn.Clicked += (object s, EventArgs e) =>
    {
        int var1 = 1;
        int var2 = 0;
        // Cause a DivideByZeroException
        var1 /= var2;
    };
}

However, the event handler is never triggered, app breaks and Debug window says the exception is still unhandled. What am I missing?

Upvotes: 1

Views: 3339

Answers (1)

AbbyWang - MSFT
AbbyWang - MSFT

Reputation: 650

Actually, the debug message is printed before the app is forced to shut down.

If you add a breakpoint at the end of CurrentDomain_UnhandledException function(In the capture below, the breakpoint is on line30)you will see that.

enter image description here

Upvotes: 2

Related Questions