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

Ton*_*nyI 1 c# exception

我必须进行代码审查,然后进入处理可能的异常的代码部分。在我看来,开发人员编码有效,但是我想问一下通常的正确方法是什么。捕获异常的最佳方法是什么?编码员写道:

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

我以为这本书说应该是:

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

Dar*_*dan 6

第二种方法将更可取。但是,建议的解决方案与当前解决方案之间没有什么区别。您需要重构为一种方法,或在两个位置(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
  }
Run Code Online (Sandbox Code Playgroud)

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

  • 我本人正在努力将其用作答案,但我更喜欢您的解释。:-) (3认同)
  • 我喜欢这个答案,因为它并不是很严格。最终,它尽可能清晰地表达了逻辑(并防止了白痴)。 (3认同)