Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c# - Throwing an exception vs Contract.Requires<T>?

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

For example:

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

    // ...
}

vs

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

    // ...
}

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

This is my consideration:

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: Static tools support (e.g. inform the caller of contract violation).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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: 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.

Hope this clear things up.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...