【问题标题】:Where is the exception caught? (Try/Catch)异常在哪里捕获? (试着抓)
【发布时间】:2016-10-05 15:34:03
【问题描述】:

当使用后台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);
   }
}

调用:backgroundWorker1.RunWorkerAsync();

有没有办法确保在方法中处理异常?所以后台工作人员不会中断?

【问题讨论】:

  • 哪个例外? "so the backgroundworker doesn't break" - 表示上面的代码有问题,哪些问题?
  • 如果您的DoWork 函数中未处理异常,那么它将作为参数的一部分传递给您的RunWorkerCompleted 函数。见this related question
  • 放一个断点,或者在日志中添加一些东西,看看是哪一个写出来的。任何一个都只需要你几秒钟的时间来检查。
  • 没有服务,没有。当 backgroundworker 类在 VS2015 中中断时,它不会向您显示中断的位置。因此我的问题

标签: c# exception try-catch


【解决方案1】:

因为这个捕获“更接近”“错误”

这个:

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

【讨论】:

    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 2018-04-03
    • 2020-01-11
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多