sab669
sab669

Reputation: 4104

How does the AppDomain.UnhandledException event work?

I was reading over the MSDN page about the event (http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.110).aspx), and I get that it can be used to handle exceptions that your "actual" code doesn't catch, but I don't understand how it works in this sense:

This event can be handled in any application domain. The event is not necessarily raised in the app domain where it occurred

Is each project considered a different Application Domain? I thought the whole solution was one domain. Further more, what separates this event from the Application.ThreadException event? Is this just another "catch all" to throw in the Program file incase something doesn't get handled by the other code?

Upvotes: 2

Views: 492

Answers (1)

Hans Passant
Hans Passant

Reputation: 941287

The rest of the note in the MSDN article is important:

An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated.

"Where the thread originated" is the important detail, the code might have been called from another AppDomain through the proxy created by AppDomain.CreateInstanceFromAndUnwrap or ExecuteAssembly, the basic ways in you get code to run in another AppDomain. Otherwise the key reason that a class derived from System.Exception should have a constructor that takes a SerializationInfo, the mechanism by which an exception gets serialized from one AD to another.

Very obscure details, using AppDomains is an advanced programming technique. AppDomains don't have anything to do with projects. You should normally only ever concern yourself with subscribing the AppDomain.CurrentDomain.UnhandledException event, do so in your Main() method.

Application.ThreadException is an implementation detail for Winforms. It only signals unhandled exceptions that are raised on the UI thread. The underlying assumption is that an unhandled exception in an event handler is not necessarily fatal since such event handlers rarely have a significant impact on the state of the program. So handling the exception and allowing the program to continue running is technically possible.

This is a pretty questionable assumption since crashes in some event handlers will certainly have an impact and you cannot know exactly which event handler caused the exception. A best practice therefore is to not allow that event to be raised. Call Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException) to disable the event, your AppDomain.UnhandledException event handler will now be used, like it will for any unhandled exception.

Upvotes: 4

Related Questions