我必须进行代码审查,然后进入处理可能的异常的代码部分。在我看来,开发人员编码有效,但是我想问一下通常的正确方法是什么。捕获异常的最佳方法是什么?编码员写道:
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)
第二种方法将更可取。但是,建议的解决方案与当前解决方案之间没有什么区别。您需要重构为一种方法,或在两个位置(NotSupportedException
和IOException
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
}
Run Code Online (Sandbox Code Playgroud)
如果这不是强制性的,则可以按原样保留实现