你可以在每个区块中捕获多种类型的异常吗?

Mat*_*ley 15 c# try-catch

这个问题接近我想做的事情,但并不完全存在.

有没有办法简化以下代码?

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;
}
Run Code Online (Sandbox Code Playgroud)

这似乎是浪费,如果我以后想要改变向用户报告错误的方式,或者我想记录这些错误,或者其他什么,那么我必须更改5个不同的catch块.我错过了一些东西,还是公然反对代码重用?

我只是想(太)懒惰吗?

Lot*_*tfi 23

您可以使用 :

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;
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*hen 8

如果异常共享一个共同的超类,那么你可以捕获超类.