首页 > 解决方案 > 捕获异常的推荐方法是什么

问题描述

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

  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
  }

标签: c#exception

解决方案


第二种方法会更受欢迎。但是,提议的解决方案与当前解决方案之间存在微小差异。您需要重构一个方法,或者将代码复制到两个地方(NotSupportedExceptionIOExceptioncatch 块),而当前的实现在同一个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
  }

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


推荐阅读