Reputation: 721
First time I've worked with Xamarin and am still coming to grips with some of the basics.
See my example below
protected override void OnCreate(Bundle bundle)
{
try
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Login);
Button button = FindViewById<Button>(Resource.Id.Login);
button.Click += delegate
{
throw new Exception("button exception");
};
}
catch(Exception e)
{
}
}
I've simplified the code above to get straight to the point.
I'm in the process of setting up some generic error handling for inside my activities, and as an example I've thrown an exception when clicking on the button. Despite this being wrapped in a try/catch the exception is being thrown as an "unhandled exception".
Hoping someone can explain how this code is logically running, I'm assuming it's some sort of threading issue? How would I best handle this situation?
The end goal is that I'm looking to make some internal calls to log in; return any error messages and then bubble this up with a message box. Unfortunately I don't seem to be able to capture them.
Thanks.
I've tried setting a global handler like suggested with the following code:
protected override void OnCreate(Bundle bundle)
{
try
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
base.OnCreate(bundle);
SetContentView(Resource.Layout.Login);
Button button = FindViewById<Button>(Resource.Id.Login);
string accountCode = Resource.Id.AccountCode.ToString();
string password = Resource.Id.Password.ToString();
button.Click += delegate
{
throw new Exception("Invalid account code or password. Please try again.");
};
}
catch(Exception e)
{
}
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
throw new Exception("AH HA!");
}
Upvotes: 3
Views: 4857
Reputation: 21191
Something like this should work:
button.Click += (sender, event) =>
{
try
{
throw new Exception("button exception");
}
catch(Exception ex)
{
}
};
Basically, the try/catch goes in the delegate (which I've changed to a lambda, here). If you're going to have a long-running process, consider making it async/await compatible:
button.Click += async (sender, event) =>
{
try
{
throw new Exception("button exception");
}
catch(Exception ex)
{
}
};
Upvotes: 4
Reputation: 10566
It is because your catch is scoped only to OnCreate method, it will catch exception that are thrown inside of this method. Your click handler is invoked outside of the OnCreate method hence your catch does not work there.
As possible solution take a look here: .NET Global exception handler in console application
Upvotes: 1