我知道BackgroundWorker
会使用无法处理的异常并将其传递给RunWorkerCompleted
e.Error
属性,并且正确处理异常的方法是检查e.Error != null
。
在DoWork
事件的方法中,我有几个try
catch
块,但只有其中一些像FailedOperationException
正在工作。如果我的代码试图访问一个类在一个不可用的dll中,抛出FileNotFoundException
,这不会被更明亮的FileNotFoundException
或Exception
捕获块所引发。而不是那样,它转到e.Error
的{{1}}属性。
为什么只有部分例外被捕?
代码:
RunWorkerCompleted
try
{
SqlConnection connection = new SqlConnection(Properties.Settings.Default.CharityConnectionString);
String dataSource = connection.DataSource;
if (((ActionType)e.Argument) == ActionType.Backup)
{
try
{
lblWait.Text = "Starting backup operation ...";
ServerConnection serverConnection = new ServerConnection(dataSource);
Server sqlServer = new Server(serverConnection); // The exception is thrown here
String originalBackupPath = fileName;
BackupDeviceItem backupDevice = new BackupDeviceItem(originalBackupPath, DeviceType.File);
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = "Charity";
backup.Devices.Add(backupDevice);
backup.Initialize = true;
backup.Checksum = true;
backup.ContinueAfterError = true;
backup.Incremental = false;
backup.LogTruncation = BackupTruncateLogType.Truncate;
backup.SqlBackup(sqlServer);
MessageBox.Show("Backup was successfull", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (FileNotFoundException ex) // this catch doesn't work for FileNotFoundException exceptions
{
MessageBox.Show("Error in operation" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (FailedOperationException)
{
MessageBox.Show("Access to the selected folder is denied", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception) // and this catch doesn't work for FileNotFoundException, too
{
MessageBox.Show("Error in operation", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch(Exception)
{
MessageBox.Show("Error in operation", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
消息“无法加载文件或程序集.Microsoft.SqlServer.ConnectionInfo ”仅显示在FileNotFoundException
中。我知道如何通过私有安装程序集来解决此异常。
答案 0 :(得分:0)
我的猜测是你有异常错误。您是否正在InnerException
中查看e.Error
?
此代码按预期工作:
using System;
using System.ComponentModel;
using System.IO;
using System.Threading;
class Program
{
static void Main(string[] args)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
try
{
throw new FileNotFoundException();
}
catch (FileNotFoundException)
{
Console.WriteLine("FileNotFoundException caught");
}
};
worker.RunWorkerCompleted += (s, e) =>
{
if (e.Error != null)
Console.WriteLine("RunWorkerCompleted error is {0}", e);
};
worker.RunWorkerAsync();
while (worker.IsBusy)
Thread.Sleep(1);
}
}