This question is close to what I want to do, but not quite there.
Is there a way to simplify the following code?
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;
}
It seems a waste, and if I later want to change how I report an error back to the user, or perhaps I want to log these errors, or whatever, then I've got to change 5 different catch blocks. Am I missing something, or is this blatantly against code-reuse?
Am I just trying to be (too) lazy?
You can use :
catch (SystemException ex)
{
if( (ex is IOException)
|| (ex is UnauthorizedAccessException )
// These are redundant
// || (ex is PathTooLongException )
// || (ex is DirectoryNotFoundException )
|| (ex is NotSupportedException )
)
lblBpsError.Text = ex.Message;
else
throw;
}
If the exceptions share a common super-class then you can just catch the superclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With