2

I'm trying to log all exceptions in a xml file, so what I did is create a UnhandledException method that will be calling every time an exception is generated, a little example:

public MainWindow()
{
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionTrapper);

    InitializeComponent();
    throw new Exception("this is an example");
}

public static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{

    Console.WriteLine(e.ExceptionObject.ToString()); //Here there is breakpoint
    Environment.Exit(1);
}

Now the problem is that the method UnhandledExceptionTrapper is called only when an exception happen inside the main thread, infact I execute all the main methods inside different Tasks, an example:

 Task.Factory.StartNew(() =>
 {
     //heavy operations
     foo();
 })
 .ContinueWith((prevTask) =>
 {
     //final operations
 });

now when an exception happen in foo() for example:

public void Foo()
{
    throw new Exception("another example");
}

the method UnhandledExceptionTrapper it's not called. On the official documentation:

Occurs when an exception is not caught.

I don't understand if this working on all application (also task), or just main thread.

Thanks for any explaination.

pivutali
  • 161
  • 1
  • 12
  • I don't think the exception will propagate back to `MainWindow()` from tasks. Is `Foo()` is in the same class as `MainWindow()`? – Jacob Barnes Nov 22 '17 at 15:21
  • @JacobBarnes nope is on another class, my is just an example.. So there is no way to get all exceptions of software from MainWindow? – pivutali Nov 22 '17 at 15:26
  • Check this out: https://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx – Jacob Barnes Nov 22 '17 at 15:34
  • And this: https://stackoverflow.com/questions/12980712/what-is-the-best-way-to-catch-exception-in-task – Jacob Barnes Nov 22 '17 at 15:35
  • This story is not accurate, you are confusing it with the way the Application.UnhandledException event works. The AppDomain event works for any thread. Except the UI thread as long as you don't take the sting out of the Application event. Use Application.SetUnhandledExceptionMode(). – Hans Passant Nov 22 '17 at 17:07
  • @HansPassant I don't find this method – pivutali Nov 22 '17 at 19:04

0 Answers0