繁体   English   中英

捕获异常的推荐方法是什么

[英]What is the recommended way to catch exceptions

我必须进行代码审查,并且我得到了解决可能异常的代码部分。 在我看来,开发人员编码是有效的,但我想问一下通常和正确的方法是什么。 捕获异常的最佳方法是什么? 编码员写道:

  try 
  { . . . }
  catch (Exception ex)
  {
    if (ex is PlatformNotSupportedException)
    { //for the Windows version or edition that does not support.
    // tracing
    }
    else if (ex is NotSupportedException || ex is IOException)
    { // for the NTFS not supported or EFS is not configured
      // tracing
    }
    else
    {
      //report any exception as encrypt/decrypt
    }
  }

我认为这本书说它应该是:

  catch (PlatformNotSupportedException pnse)
  {
    //for the Windows version or edition that does not support.
    // tracing
  }
  catch (NotSupportedException nse)
  {
    // for the NTFS not supported or EFS is not configured
    // tracing
  }
  catch (IOException ioe)
  {
    // tracing for IOE
  }   
  catch (Exception e)
  {
      //report any exception as encrypt/decrypt
  }

第二种方法会更受欢迎。 但是,提议的解决方案与当前解决方案之间存在微小差异。 您需要重构一个方法,或者将代码复制到两个地方( NotSupportedExceptionIOException catch 块),而当前实现在相同的if块下处理它。

因此,如果您想遵循相同的方法,您可以使用when 关键字过滤掉某些类型等等。

  catch (PlatformNotSupportedException pnse)
  {
    // for the Windows version or edition that does not support.
    // tracing
  }
  catch (Exception ex) when (ex is NotSupportedException || ex is IOException)
  {
    // for the NTFS not supported or EFS is not configured
    // tracing
  } 
  catch (Exception e)
  {
      //report any exception as encrypt/decrypt
  }

如果这不是强制性的,您可以按原样保留实施

TLDR:使用第二种形式,以便编译器捕获排序错误。

您应该使用第二种形式的原因是,如果您尝试以错误的顺序处理类型,则会出现编译错误。

例如,这会给你一个实际的编译器错误:

try
{
    throw new ArgumentOutOfRangeException();
}

catch (Exception)
{
    Console.WriteLine("Caught 'Exception'");
}

// This gives a compile error:
// "Error CS0160  A previous catch clause already catches all exceptions of this or of a super type ('Exception')"

catch (SystemException)
{
    Console.WriteLine("Caught 'SystemException'");
}

但是,使用if/else if不会导致编译错误,因此错误不会被注意到:

try
{
    throw new ArgumentOutOfRangeException();
}

catch (Exception ex)
{
    if (ex is Exception)
    {
        Console.WriteLine("Caught 'Exception'");
    }
    else if (ex is SystemException) // This will never be reached, but no compile error.
    {
        Console.WriteLine("Caught 'SystemException'");
    }
}

但是请注意,Resharper 等工具会针对第二种情况发出警告。

这对于所有类型的异常都是通用的

try 
{
   .....code
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM