-2

When using the back ground worker class to call a method within a try catch statement, and a try catch statement is in the method, which one catches the exception?

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    try
    {
        Do();
    }
    catch (Exception ex)
    {
        System.Windows.MessageBox.Show("Error:" + e.Result + ex.Message);
    }
}

And:

private void Do ()
{
   try
   {
       //Do something, open a file etc.
       FileStream fs = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
   }
   catch (Exception e)
   {
       System.Windows.MessageBox.Show("Error:" + e.Result + ex.Message);
   }
}

Called with: backgroundWorker1.RunWorkerAsync();

Is there a way to make sure the exception is handled within the method? so the backgroundworker doesn't break?

Alberto Spelta
  • 3,578
  • 2
  • 21
  • 20
Jack Miller
  • 325
  • 1
  • 16
  • Which exception? *"so the backgroundworker doesn't break"* - indicates you have some problem with code above, which problems? – Sinatr Oct 05 '16 at 15:36
  • If an exception is unhandled in your `DoWork` function, then it will be passed as part of the arguments to your `RunWorkerCompleted` function. See [this related question](http://stackoverflow.com/questions/258662/unhandled-exceptions-in-backgroundworker). – Charles Mager Oct 05 '16 at 15:41
  • 1
    Put in a breakpoint, or add something to the log to see which one is writing it out. Either would have taken you only a few seconds to check. – Servy Oct 05 '16 at 15:41
  • No Servy, no. when the backgroundworker class breaks in VS2015, it doesn't show you where it breaks. Hence my question – Jack Miller Dec 09 '16 at 22:36

1 Answers1

1

The inner one since this catch is "closer" to the "error"

this one :

private void Do ()
{
   try
   {
       //Do something, open a file etc.
       FileStream fs = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
   }
   catch (Exception e)
   {
       System.Windows.MessageBox.Show("Error:" + e.Result + ex.Message);
   }
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95