First of all, you need to catch all exception which may be thrown inside the main event loop of the UI thread.
First, you need to get
Application.ThreadException
triggered so
don't forget this (in
Main()
):
Application.SetUnhandledExceptionMode(
UnhandledExceptionMode.CatchException);
ThreadException handler should be set up like this:
Application.ThreadException += (sender, args) => {
MessageBox.Show(string.Format(
"{0}:\n\n{1}", args.Exception.GetType().Name,
args.Exception.Message),
string.Format(
" {0}: Error", ProductName),
MessageBoxButtons.OK, MessageBoxIcon.Error);
};
If you have other threads, you generally need to catch all exceptions on the very top stack frame of each thread.
This is the very basic level of exception handling in a Form application. Other cases are semantic, you should know better where to catch them. Many beginners catch too much, blocking propagation of exceptions, which is very bad. There are very few cases when blocking of exception propagation is acceptable or needed. You don't need to catch exceptions where the are thrown, you need to catch them in the frame where you know exactly how can you fix the effect of exception, in all other cases just let them go.
—SA