【发布时间】:2011-11-28 01:36:43
【问题描述】:
这是来自自定义 Microsoft .NET 运行时实现的代码,我有以下问题:
public static string ToBase64String(byte[] inArray, int offset, int length)
{
if (inArray == null) throw new ArgumentNullException("inArray");
if (offset < 0) throw new ArgumentOutOfRangeException("offset");
if (length < 0) throw new ArgumentOutOfRangeException("length");
if (offset + length > inArray.Length)
throw new ArgumentException("offset + length > inArray.Length");
// Fast return for the zero length case, note that this scenario is
// absolutely valid.
if (length == 0) return "";
// ....
}
检查此方法的先决条件(代码合同) 的语句不应该实际上是 assert-like 的吗? 我的意思是,抛出异常的意识形态在哪里? for code contract 违规从何而来?
下面的代码我很容易理解:
Contract.Requires(inArray != null);
Contract.Requires(offset >= 0);
// ...
但是抛出不同的异常...... 为什么?
不可能正确处理这种异常,因为它只是表明逻辑缺陷,这个错误类似于Java中的unchecked exception,当你也甚至不应该尝试处理它的时候。
现在 - 我说得对吗?也许我不了解一些基本原理或倾向于过度设计所有内容?
【问题讨论】:
标签: c# java exception code-contracts