Debug.Assert 与特定抛出的异常 [英] Debug.Assert vs. Specific Thrown Exceptions

查看:32
本文介绍了Debug.Assert 与特定抛出的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始浏览 John Robbins 撰写的调试 MS .Net 2.0 应用程序",并被他对 Debug.Assert(...) 的宣传弄糊涂了.

I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...).

他指出,实施良好的断言在某种程度上存储了错误条件的状态,例如:

He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.:

Debug.Assert(i > 3, "i > 3", "This means I got a bad parameter");

现在,就我个人而言,他如此喜欢在没有实际合理的业务逻辑"评论的情况下重述他的测试,这对我来说似乎很疯狂,也许由于 flobittyjam widgitification 过程,i <= 3 绝不能发生".

Now, personally, it seems crazy to me that he so loves restating his test without an actual sensible 'business logic' comment, perhaps "i <= 3 must never happen because of the flobittyjam widgitification process".

所以,我认为我将断言作为一种低级别的让我们保护我的假设"之类的东西......假设人们觉得这是一个只需要在调试中进行的测试 - 即你正在保护自己反对同事和未来的程序员,并希望他们实际测试.

So, I think I get Asserts as a kind-of low-level "Let's protect my assumptions" kind of thing... assuming that one feels this is a test one only needs to do in debug - i.e. you are protecting yourself against colleague and future programmers, and hoping that they actually test things.

但我不明白的是,他接着说除了正常的错误处理之外,你还应该使用断言;现在我的设想是这样的:

But what I don't get is, he then goes on to say that you should use assertions in addition to normal error handling; now what I envisage is something like this:

Debug.Assert(i > 3, "i must be greater than 3 because of the flibbity widgit status");
if (i <= 3)
{
    throw new ArgumentOutOfRangeException("i", "i must be > 3 because... i=" + i.ToString());
}

我通过 Debug.Assert 重复错误条件测试获得了什么?如果我们谈论的是对非常重要的计算进行仅调试的双重检查,我想我会明白的...

What have I gained by the Debug.Assert repetition of the error condition test? I think I'd get it if we were talking about debug-only double-checking of a very important calculation...

double interestAmount = loan.GetInterest();
Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc");

...但我没有得到它肯定值得检查的参数测试(在调试和发布版本中)...或不.我错过了什么?

...but I don't get it for parameter tests which are surely worth checking (in both DEBUG and Release builds)... or not. What am I missing?

推荐答案

断言不用于参数检查.应始终进行参数检查(并准确地根据您的文档和/或规范中指定的前置条件),并在必要时抛出 ArgumentOutOfRangeException.

Assertions are not for parameter checking. Parameter checking should always be done (and precisely according to what pre-conditions are specified in your documentation and/or specification), and the ArgumentOutOfRangeException thrown as necessary.

断言用于测试不可能"的情况,即您(在您的程序逻辑中)假设为真的事情.断言是为了告诉您这些假设是否因任何原因被打破.

Assertions are for testing for "impossible" situations, i.e., things that you (in your program logic) assume are true. The assertions are there to tell you if these assumptions are broken for any reason.

希望这有帮助!

这篇关于Debug.Assert 与特定抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆