You can add the event handler anywhere, but it's best to do it as
early as possible so that the minimum amount of code runs before the
handler is hooked up.
Yes, so that it's set up to handle an exception even from the
initialization code you have.
There is also the Application.ThreadException event. I always handle
them both.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpre...
Ok, I'll look into that. What are ThreadExceptions? Like when a GUI
control is attempted to be accessed by another thread?
Main, by the way, is the main entry point into any application,
console or WinForms. It is usually the first piece of your code that
the CLR calls, and it's usually where you set up global exception
handlers.
Right, I should have known that, but I didn't know where it was hidden
in the Windows app.
Well, not necessarily. For example, I have mine in a standard error
logging class, and from my Main I call something like:
ErrorLog.Instance.SetupConsoleErrorHandling();
Ok, I just placed mine elsewhere, and it works, as long as I give
Program class access to it.
Hmm, I jus tested my program with Ctrl+F5 (not F5 debug), and an
unhandled exception window pops up. It appears that my handler
doesn't run. But, it does run if I used F5 debug. Strange.
and inside there I subscribe to the events and the ErrorLog class
contains the event handler methods. Nonetheless, that's just because I
wanted a reusable utility. You can also have the method in your main
program .cs file. Nothing wrong with that.
Right, but its best to have a unit handle this that can be reused, I
agree. So, your ErrorLog class adds the handler, and hopefully this
code is run before any other code that could throw an exception.
Finally, I would like to offer some general advice on catching
exceptions: catch only what you can handle. Or, put another way, don't
catch an exception unless you can take some substantial action
regarding it. There are other threads in this newsgroup on exception
handling... when and how to catch an exception, but I wanted to point
that out because it explains why you (almost) never catch (Exception
ex): because it's very rare that you can take some intelligent action
with any exception that could possible happen.
Yes, I agree. And my main concern was exceptions for things that are
bound to happen, such as int.Parse() or dealing with network traffic,
who knows what data may be passed into these functions, or what
network errors may result. So, in these case, I do want to handle ALL
errors gracefully. But, it seemed ugly to write 5 exceptions handlers
OR catch all excpetions with catch (Exception ex). For int.Parse, I
can use int.TryParse. For networkd traffic, it really seems ok to
catch everything. It'd be different if all the possible exceptions
were under the same exception type, but they are not.
The exception to that rule, of course, being logging, and that's what
global exception handlers are for.
Right.
Zytan