C#和Java(以及太多其他语言)在许多类型中都具有某些“溢出”行为,我根本不喜欢它(例如:
type.MaxValue + type.SmallestValue == type.MinValue
,例如: int.MaxValue + 1 == int.MinValue
)。但是,鉴于我的恶毒天性,我会将此行为扩展到比如重写的类型。 (我知道在.NET中是sealed的,但为了这个例子,我使用了一种与C#完全相同的伪代码,除了DateTime不是sealed之外)。
重写的方法:
/// <summary>
/// Increments this date with a timespan, but loops when
/// the maximum value for datetime is exceeded.
/// </summary>
/// <param name="ts">The timespan to (try to) add</param>
/// <returns>The Date, incremented with the given timespan.
/// If DateTime.MaxValue is exceeded, the sum wil 'overflow' and
/// continue from DateTime.MinValue.
/// </returns>
public DateTime override Add(TimeSpan ts)
{
try
{
return base.Add(ts);
}
catch (ArgumentOutOfRangeException nb)
{
// calculate how much the MaxValue is exceeded
// regular program flow
TimeSpan saldo = ts - (base.MaxValue - this);
return DateTime.MinValue.Add(saldo)
}
catch(Exception anyOther)
{
// 'real' exception handling.
}
}
当然,if语句同样可以轻松解决这个问题,但事实仍然是我不明白为什么不能使用异常(从逻辑上讲,我可以看出在某些情况下应该避免使用异常来提高性能)。我认为在许多情况下,异常比if结构更清晰,并且不会违反方法所做的任何契约。
我认为,“永远不要将它们用于常规程序流程”这种反应并不像人们似乎认为的那么有根据,因为这种反应的强度无法证明。
或者我错了吗?
我已经阅读了其他帖子,涉及各种特殊情况,但我的观点是,如果你既清晰又尊重你方法的契约,那么使用异常也没有什么问题。
别打我。