c# - C# 抛出异常并以相同的方法捕获它为什么不好?
问题描述
对一种实现进行一些讨论:
// Pseudocode
accessor type GetValue()
{
try
{
do some action with possible throw exception1
do some action with possible throw exception2
return value;
}
catch (Exception ex)
{
value = default;
throw Wraped in Meaningfull Exception ex
}
}
有人可以解释为什么使用它可能是一个糟糕的设计try
-catch
像这样(以相同的方法抛出和捕获)来安全地执行一些操作并聚合不同类型的类似异常吗?
解决方案
这不是重新抛出
throw new WrapedException("MyNewMessage", ex);
这是错误的,但捕获所有异常
catch (Exception ex) {
...
}
是一个糟糕的设计:它掩盖了潜在的危险行为。让我们看看为什么。假设我们这样使用GetValue()
:
try {
someValue = GetValue();
}
catch (WrapedException) {
// We failed to obtain someValue;
// The reason - WrapedException - is innocent
// Let's use default value then
someValue = defaultSomeValue;
}
而实际图片是
public GetValue() {
try {
do some action with possible throw exception1
// Catastrophy here: AccessViolationException! System is in ruins!
do some action with possible throw exception2
return value;
}
catch (Exception ex) { // AccessViolationException will be caught...
// ...and the disaster will have been masked as being just WrapedException
throw new WrapedException("MyNewMessage", ex);
}
}
如果您只捕获预期的异常类型,您的设计是可以的:
public GetValue() {
try {
do some action with possible throw exception1
do some action with possible throw exception2
return value;
}
catch (FileNotFound ex) {
// File not found, nothing special in the context of the routine
throw new WrapedException("File not found and we can't load the CCalue", ex);
}
}
推荐阅读
- r - 没有目标的networkD3 sankey图节点?
- sql-server - 使用 Alter Database 选项创建过程
- r - 如何选择与R中列表中的项目相等的行?
- intellij-idea - PhpStorm Live Templates 的 Groovy 脚本给出建议框?
- node.js - 如何将数据从mongodb发送到express js中的get方法
- android - android如何在响应错误时删除代码缓存
- python - 如何汇总引用其他数据框的总数
- php - PHP AJAX JSON - 将输入转换为 JSON 和其他 PHP 文件获取价值
- javascript - 如何为隐藏/显示编写此代码 - 添加/删除类 - 在 jQuery 中更优化?
- python - Python:如何将系列/列中的相同数字更改为其他值?