我知道它会BackgroundWorker
吃未经处理的异常并将它们传递给RunWorkerCompleted
e.Error
属性,并且处理异常的正确方法是检查e.Error != null
.
在DoWork
事件的方法中,我有几个try
catch
块,但只有其中一些块在工作。如果FailedOperationException
我的代码试图访问不可用的 dll 中的类,则会FileNotFoundException
抛出一个不会被邻居FileNotFoundException
或Exception
捕获块捕获的类。取而代之的是,它e.Error
属于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);
}
FileNotFoundException
带有消息“无法加载文件或程序集。Microsoft.SqlServer.ConnectionInfo ”仅显示在e.Error
. 我知道如何通过私人安装程序集来解决此异常。