c# - 捕获异常的推荐方法是什么
问题描述
我必须进行代码审查,并且我得到了解决可能异常的代码部分。在我看来,开发人员编码是有效的,但我想问一下通常和正确的方法是什么。捕获异常的最佳方法是什么?编码员写道:
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
}
解决方案
第二种方法会更受欢迎。但是,提议的解决方案与当前解决方案之间存在微小差异。您需要重构一个方法,或者将代码复制到两个地方(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
}
如果这不是强制性的,您可以按原样保留实施
推荐阅读
- javascript - 使用“CanvasRenderingContext2D.putImageData()”时出现白屏,即使数据似乎包含图像
- c# - 如何从文件存储中异步下载数百万个文件?
- php - 为什么当 nl2br 工作正常时 PHP_EOL 不工作
- azure-ad-b2c - 只有“电子邮件”字段可以通过“id_token_hint”传递给 B2C 自定义策略
- php - Google 日历 API 保持帐户连接
- c# - 如何使用 EditForm 将必填字段的日期默认为今天的日期?
- solr - 使用 curl 创建 solr 集合
- javascript - forEach 与 Firebase 调用
- c - 当程序期望C中的int时传递字符串
- r - http://localhost:8000/mapTiles/OSM/{z}_{x}_{y}.png 不工作 - SHINY R