I have Visual Studio C# app where the main form keeps a log of the
application's status. For several of the event handlers and methods in the
main form, I have try/catch blocks. But adding try/catch blocks to every
method is rather painful, especially when most of them do the same thing
anyway; which is to record the exception details to the log and show them in
a TextBox.
I am looking for a way that I can create a default event handler to do this.
The catch is, that the default event handler must have visibility to the
logging function in the scope of the main form.
I have tried adding an event handler to Application.ThreadException like this:
Application.ThreadException += new
ThreadExceptionEventHandler(DefaultExceptionHandle r);
where DefaultExceptionHandler is defined in the main form class and does all
the necessary logging.
The problem is, I needed to place the above code in the constructor of my
form for the DefaultExceptionHandler to be visible. Although this did not
cause any compile or runtime errors, unhandled exceptions did not seem to
call out the DefaultExceptionHandler (as if it wasn't even there). I suspect
this might be because I need to put the above statement in my code BEFORE
Application.Run() is called, and not in the main form constructor. (Please
correct me if I am wrong.) But if I do this, then I no longer have
visibility to my main form, because the Application.Run() is called from the
static class Main.
Also, it is my understanding that the ThreadEventExceptionHandler will
terminate the application. For this app, I can determine whether the
exception that occurred is fatal or not, so I would really like to have
control over whether the app terminates or continues. Can I somehow prevent
the standard ThreadEventExceptionHandler code from executing so that only my
DefaultExceptionHandler executes?