Jack Miller Jack Miller - 2 months ago 6
C# Question

Where is the exception caught? (Try/Catch)

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?

Answer

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);
   }
}