我必须进行代码审查,然后进入处理可能的异常的代码部分。在我看来,开发人员编码有效,但是我想问一下通常的正确方法是什么。捕获异常的最佳方法是什么? 编码员写道:
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
}
答案 0 :(得分:6)
第二种方法更可取。但是,建议的解决方案与当前解决方案之间没有什么区别。您需要重构为一种方法,或者将代码复制到两个位置(NotSupportedException
和IOException
catch块),而当前实现则在同一if
块下处理它。>
因此,如果您想采用相同的方法,则可以使用when
keyword来过滤某些类型和更多类型。
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
}
如果这不是强制性的,则可以按原样保留实现方式
答案 1 :(得分:2)
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之类的工具会在第二种情况下警告您。
答案 2 :(得分:0)
这对于所有类型的异常都是通用的
try
{
.....code
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}