Alright, this is an easy one:
What's the difference between
Application.ThreadExceptionandAppDomain.CurrentDomain.UnhandledException?Do I need to handle both?
Thanks!
Alright, this is an easy one:
What's the difference between Application.ThreadException and AppDomain.CurrentDomain.UnhandledException?
Do I need to handle both?
Thanks!
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.
OK - I had it in front of me, this bit of code from msdn is pretty self-explanatory:
public static void Main(string[] args)
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new
ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms
// errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// Runs the application.
Application.Run(new ErrorHandlerForm());
}
Well the thing is, ThreadException occurs due to a problem with your thread, the Unhandled Exception is fired if you code throws an exception that is not handled.
Easist way to cause the second one is to create an app with no try...catch blocks and throw an exception.
Now if you need insurance you can handle them both, however if you capture and handle your exceptions correctly then you should not need the UnhandledException handler as it's kind of like a catch all.