Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

try-catch

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?

like image 612
Matthew Scharley Avatar asked Aug 20 '09 09:08

Matthew Scharley


2 Answers

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;
}
like image 62
Lotfi Avatar answered Oct 13 '22 11:10

Lotfi


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

like image 20
Benedict Cohen Avatar answered Oct 13 '22 10:10

Benedict Cohen