C# - WinForms - Exception Handling for Events
- by JustLooking
Hi all, I apologize if this is a simple question (my Google-Fu may be bad today).
Imagine this WinForms application, that has this type of design: Main application - shows one dialog - that 1st dialog can show another dialog. Both of the dialogs have OK/Cancel buttons (data entry).
I'm trying to figure out some type of global exception handling, along the lines of Application.ThreadException. What I mean is:
Each of the dialogs will have a few event handlers. The 2nd dialog may have:
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
AllSelectedIndexChangedCodeInThisFunction();
}
catch(Exception ex)
{
btnOK.enabled = false; // Bad things, let's not let them save
// log stuff, and other good things
}
}
Really, all the event handlers in this dialog should be handled in this way. It's an exceptional-case, so I just want to log all the pertinent information, show a message, and disable the okay button for that dialog.
But, I want to avoid a try/catch in each event handler (if I could). A draw-back of all these try/catch's is this:
private void someFunction()
{
// If an exception occurs in SelectedIndexChanged,
// it doesn't propagate to this function
combobox.selectedIndex = 3;
}
I don't believe that Application.ThreadException is a solution, because I don't want the exception to fall all the way-back to the 1st dialog and then the main app. I don't want to close the app down, I just want to log it, display a message, and let them cancel out of the dialog. They can decide what to do from there (maybe go somewhere else in the app).
Basically, a "global handler" in between the 1st dialog and the 2nd (and then, I suppose, another "global handler" in between the main app and the 1st dialog).
Thanks.