I have used Application.ThreadException and AppDomain.CurrentDomain.UnhandledException before but usually I only use this for a single form. So usually I would use the Main in Program.cs.
try {
AppDomain.CurrentDomain.UnhandledException += (sender, e) => .Handle(sender, (Exception)e.ExceptionObject);
Application.ThreadException += (sender, e) => ExceptionHandler.Handle(sender, e.Exception);
Application.Run(ApplicationBase);
} catch (Exception ex) {
MessageBox.Show("Handled Exception");
}
In my new situation however I have a host of forms for my current project with a single base form that the other forms inherit from.
What I am trying to do is handle exceptions that are thrown in a derived form within code from the base form – I plonked the above code into my base’s constructor hoping I could do it that way but when there is an exception, it doesn’t hit the event.
Any reason why I can’t do this in the constructor and any alternatives?
NOTE: I previously asked this in Vb.net instead of C# so deleted my previous question and refactored my code so I could have a C# answer.
Those events are global events; they have nothing to do with individual forms.
You can keep your current code in
Main()and it will work fine with multiple forms. (unless you have multiple UI threads)