What's the difference between Application.ThreadException and AppDomain.CurrentDomain.UnhandledException?

JohnIdol picture JohnIdol · Jan 6, 2010 · Viewed 26.8k times · Source

Alright, this is an easy one:

  • What's the difference between Application.ThreadException and
    AppDomain.CurrentDomain.UnhandledException?

  • Do I need to handle both?

Thanks!

Answer

Hans Passant picture Hans Passant · Jan 6, 2010

Application.ThreadException is specific to Windows Forms. Winforms runs event handlers in response to messages sent to it by Windows. The Click event for example, I'm sure you know them. If such an event handler throws an exception then there's a back-stop inside the Winforms message loop that catches that exception.

That backstop fires the Application.ThreadException event. If you don't override it, the user will get a ThreadExceptionDialog. Which allows him to ignore the exception and keep running your program. Not a great idea btw.

You can disable this behavior by calling Application.SetUnhandledExceptionMode() in the Main() method in Program.cs. Without that backstop in place, the usual thing happens when a thread dies from an unhandled exception: AppDomain.UnhandledException fires and the program terminates.

Fwiw: "ThreadException" was a very poor name choice. It has nothing to do with threads.