我认为一个(人为的)实际示例可能有助于阐明差异:
(改编自MoreLinq 的批处理扩展)
// 'public facing' method
public int DoSomething(List<string> stuff, object doohickey, int limit) {
// validate user input and report problems externally with exceptions
if(stuff == null) throw new ArgumentNullException("stuff");
if(doohickey == null) throw new ArgumentNullException("doohickey");
if(limit <= 0) throw new ArgumentOutOfRangeException("limit", limit, "Should be > 0");
return DoSomethingImpl(stuff, doohickey, limit);
}
// 'developer only' method
private static int DoSomethingImpl(List<string> stuff, object doohickey, int limit) {
// validate input that should only come from other programming methods
// which we have control over (e.g. we already validated user input in
// the calling method above), so anything using this method shouldn't
// need to report problems externally, and compilation mode can remove
// this "unnecessary" check from production
Debug.Assert(stuff != null);
Debug.Assert(doohickey != null);
Debug.Assert(limit > 0);
/* now do the actual work... */
}
因此,正如Eric Lippert等人所说,您只断言您希望正确的东西,以防您(开发人员)在其他地方不小心使用了错误,这样您就可以修复您的代码。当您无法控制或无法预料会发生什么时,您基本上会抛出异常,例如用户输入,以便任何给它的坏数据都可以适当地响应(例如用户)。