抛出异常与Contract.Requires< T>? [英] Throwing an exception vs Contract.Requires<T>?

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

问题描述

我想知道是否应该抛出异常或者调用 Contract.Requires< TException>

I'm wondering whether should I throw exceptions or call Contract.Requires<TException>

例如:

public static void Function(String str)
{
    if (str == null) throw new ArgumentNullException("str", "Input string cannot be null.");

    // ...
}

vs



vs

public static void Function(String str)
{
    Contract.Requires<ArgumentNullException>(str != null, "Input string cannot be null.");

    // ...
}

Contract.Requires< TException> / a>不需要 CONTRACTS_FULL 符号,我可以把它保存在我的发布版本中。

Since Contract.Requires<TException> doesn't require the CONTRACTS_FULL symbol I can keep it in my release builds as well.

是我的考虑:

Con:您不能调用自定义异常类型构造函数的重载版本。没有办法向构造函数传递其他参数。

Con: You can't call an overloaded version of the custom exception type constructor. There is simply no way to pass additional parameters to the constructor.

Pro:静态工具支持(例如通知呼叫者合同违规)。

Pro: Static tools support (e.g. inform the caller of contract violation).

我应该使用哪一个,以及什么样的情况?

Which one should I use, and for what kind of situation?

推荐答案

if-then-throw 之间的基本权衡需要< TException> ,如CodeContract用户指南是您使用发布位置构建的方式。

The basic trade-off between if-then-throw and Requires<TException> as documented in the CodeContract user guide is how you build with your release bits.

案例1 :您只能使用 if-then-throw ,否需要< TException> 。在这种情况下,您可以构建您的发布位,而无需在dll / exe上运行合同工具。优点是您具有更快的构建,并且没有工具引入错误的风险。第二个优点是团队成员可以选择不使用CodeContract工具。缺点是您没有获得合同继承的要求,并且您的合同不一定对工具可见(除非您使用 EndContract )。您可以使用装配模式指定此情况:自定义参数验证

Case 1: You only use if-then-throw, no Requires<TException>. In this case you can build your release bits without running the contract tools on your dll/exe. The advantage is that you have faster builds and no risk that the tool introduces bugs. A second advantage is that team members can opt out of using the CodeContract tools. Disadvantages are that you get no contract inheritance of requires, and your contracts are not necessarily visible to the tools (unless you use EndContract). You specify this case by using assembly mode: Custom Parameter Validation

Case2 :您决定始终在发布位上运行CodeContract工具。这允许您使用需要< TException> ,并获得合同的继承权,包括界面等的检测。您的合同是干净的和工具可识别的。缺点是每个构建代码的人都必须安装CodeContracts工具。您可以使用装配模式指定此情况:合同属性窗格中的标准。

Case2: You decide to run the CodeContract tools on your release bits always. This lets you use Requires<TException> and you get inheritance of contracts, including instrumentation of interfaces etc. Your contracts are clean and tool recognizable. The disadvantage is that everyone building your code must have the CodeContracts tools installed. You specify this case by using assembly mode: Standard in the Contract property pane.

希望这一点清楚。

这篇关于抛出异常与Contract.Requires&lt; T&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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