异常在哪里被捕获?(Try / Catch)

本文关键字:Try Catch 在哪里 异常 | 更新日期: 2023-09-27 18:11:44

当使用后台worker类在try catch语句中调用方法时,并且try catch语句在该方法中,哪个捕获异常?

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

:

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

call with: backgroundWorker1.RunWorkerAsync();

是否有一种方法可以确保在方法内处理异常?所以后台工人不会坏?

异常在哪里被捕获?(Try / Catch)

内部的,因为这个捕获更接近"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);
   }
}