Alex Rivera | Logout

Can you catch more than one type of exception with each block?

Asked 2009-08-20T09:49:08.387
15

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?

Edit
Report

2 Answers

8

If the exceptions share a common super-class then you can just catch the superclass.

answered 2009-08-20T09:53:35.803
0

I understand some of these exceptions may not be foreseeable but where possible try to implement your own "pre-emptive" logic. Exceptions are expensive, though in this case probably not a deal breaker.

For example, use Directory.GetAccessControl(...) rather than relying on an UnauthorizedAccessException to be thrown.

answered 2009-08-20T10:23:15.543

Your Answer