<分区>
This question is close to what I want to do , 但不完全是。
有没有办法简化下面的代码?
private bool ValidDirectory(string directory)
{
if (!Directory.Exists(directory))
{
if (MessageBox.Show(directory + " does not exist. Do you wish to create it?", this.Text)
== DialogResult.OK)
{
try
{
Directory.CreateDirectory(directory);
return true;
}
catch (IOException ex)
{
lblBpsError.Text = ex.Message;
}
catch (UnauthorizedAccessException ex)
{
lblBpsError.Text = ex.Message;
}
catch (PathTooLongException ex)
{
lblBpsError.Text = ex.Message;
}
catch (DirectoryNotFoundException ex)
{
lblBpsError.Text = ex.Message;
}
catch (NotSupportedException ex)
{
lblBpsError.Text = ex.Message;
}
}
}
return false;
}
这似乎是一种浪费,如果我以后想更改向用户报告错误的方式,或者我想记录这些错误,或者其他什么,那么我必须更改 5 个不同的 catch block 。我是否遗漏了什么,或者这是否公然反对代码重用?
我只是想变得(太)懒惰吗?