Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my exception is not making any difference in a wpf application?

I have a WPF application that has a BackgroundWorker. I throw an exception in this BGW but it is not shown any where!, just the background worker fires its WorkerFinished event.

Where is it going?

like image 873
mans Avatar asked May 17 '13 16:05

mans


2 Answers

Each thread has it's own call stack; exceptions can only move up their own call stack, there's no way for them to "bleed" over into another thread's call stack.

When your exception bubbles up to the BackgroundWorker's code that fires the DoWork event handler the exception will end up being explicitly caught and stored in the Error property rather than allowing it to reach the top of the call stack and crash the application.

If you want the program to end if your BGW throws an exception then you'll need to handle the completed event, check for an exception, and then re-throw it or throw a new exception.

like image 139
Servy Avatar answered Sep 21 '22 10:09

Servy


Look here, there's a nice example. The exception in throwned in the RunWorkercompleted

Unhandled exceptions in BackgroundWorker

var worker = new BackgroundWorker();
worker.DoWork += (sender, e) => 
    { 
        throw new InvalidOperationException("oh shiznit!"); 
    };
worker.RunWorkerCompleted += (sender, e) =>
    {
        if(e.Error != null)
        {
            MessageBox.Show("There was an error! " + e.Error.ToString());
        }
    };
worker.RunWorkerAsync();
like image 35
the_lotus Avatar answered Sep 22 '22 10:09

the_lotus