【发布时间】:2015-08-27 06:41:02
【问题描述】:
我在好设计方面遇到了困难。
我不确定是否应该让稍后的方法抛出异常,或者是否应该自己抛出异常。
事情是:
异常的类型会根据被调用的方法而变化。在后面的方法中,它可能是 InvalidOperation,但在当前方法中,ArgumentException 可能更适合。
现在我应该真正执行所有检查以抛出正确类型的异常,还是应该让更深层次的方法抛出不正确类型的异常?
考虑一下:
private bool _canWaste = false;
/// <summary>
/// Runs around and wastes something.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown when <paramref name="CanPower"/> is false.
/// </exception>
public void Run(bool CanWaste) {
_canWaste = CanWaste;
// <- Should I check if we can waste and throw an ArgumentException here or
// throw the 'wrong' type later in Waste?
Waste();
}
/// <summary>
/// Wastes something.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown when we cannot waste.
/// </exception>
private void Waste() {
if(!_canWaste) throw new InvalidOperationException("We cannot waste.");
/* ... */
}
这是一个很容易完成的简单示例(没有意义)。
但是,当然,有些方法的评估要困难得多。
另一种选择是捕获异常并抛出正确类型的新异常。
但我想这会影响性能并在输出中记录一些不酷的东西。
【问题讨论】: