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

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

<pre><code>Debug.Assert(i &gt; 3, "i &gt; 3", "This means I got a bad parameter");
</code></pre>

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

<p>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.</p>

<p>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:</p>

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

<p>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...</p>

<pre><code>double interestAmount = loan.GetInterest();
Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc");
</code></pre>

<p>...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?</p>

[{'answer_id': 61223, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': '<p>IMO it\'s a loss of development time only. Properly implemented exception gives you a clear picture of what happened. I saw <em>too much</em> applications showing obscure "Assertion failed: i &lt; 10" errors. I see assertion as a temporary solution. In my opinion no assertions should be in a final version of a program. In my practice I used assertions for quick and dirty checks. Final version of the code should take erroneous situation into account and behave accordingly. If something bad happens you have 2 choices: handle it or leave it. Function should throw an exception with meaningful description if wrong parameters passed in. I see no points in duplication of validation logic.</p>\n'}, {'answer_id': 61225, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': 7, 'selected': True, 'text': '<p>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 <code>ArgumentOutOfRangeException</code> thrown as necessary.</p>\n\n<p>Assertions are for testing for "impossible" situations, i.e., things that you (in your program logic) <em>assume</em> are true. The assertions are there to tell you if these assumptions are broken for any reason.</p>\n\n<p>Hope this helps!</p>\n'}, {'answer_id': 61237, 'author': 'Simon Johnson', 'author_id': 854, 'author_profile': 'https://Stackoverflow.com/users/854', 'pm_score': 2, 'selected': False, 'text': '<p>I use explicit checks that throw exceptions on <em>public</em> and <em>protected</em> methods and assertions on private methods.</p>\n\n<p>Usually, the explicit checks guard the private methods from seeing incorrect values anyway. So really, the assert is checking for a condition that should be impossible. If an assert does fire, it tells me the there is a defect in the validation logic contained within one of the public routines on the class.</p>\n'}, {'answer_id': 61266, 'author': 'hwiechers', 'author_id': 5883, 'author_profile': 'https://Stackoverflow.com/users/5883', 'pm_score': 4, 'selected': False, 'text': '<p>There is a communication aspect to asserts vs exception throwing.</p>\n\n<p>Let\'s say we have a User class with a Name property and a ToString method.</p>\n\n<p>If ToString is implemented like this:</p>\n\n<pre><code>public string ToString()\n{\n     Debug.Assert(Name != null);\n     return Name;\n}\n</code></pre>\n\n<p>It says that Name should never null and there is a bug in the User class if it is.</p>\n\n<p>If ToString is implement like this:</p>\n\n<pre><code>public string ToString()\n{\n     if ( Name == null )\n     {\n          throw new InvalidOperationException("Name is null");\n     }\n\n     return Name;\n}\n</code></pre>\n\n<p>It says that the caller is using ToString incorrectly if Name is null and should check that before calling.</p>\n\n<p>The implementation with both</p>\n\n<pre><code>public string ToString()\n{\n     Debug.Assert(Name != null);\n     if ( Name == null )\n     {\n          throw new InvalidOperationException("Name is null");\n     }\n\n     return Name;\n}\n</code></pre>\n\n<p>says that if Name is null there bug in the User class, but we want to handle it anyway. (The user doesn\'t need to check Name before calling.) I think this is the kind of safety Robbins was recommending.</p>\n'}, {'answer_id': 61678, 'author': 'Steve Steiner', 'author_id': 3892, 'author_profile': 'https://Stackoverflow.com/users/3892', 'pm_score': 2, 'selected': False, 'text': '<p>An exception can be caught and swallowed making the error invisible to testing. That can\'t happen with Debug.Assert.</p>\n<p>No one should ever have a catch handler that catches all exceptions, but people do it anyway, and sometimes it is unavoidable.  If your code is invoked from COM, the interop layer catches all exceptions and turns them into COM error codes, meaning you won\'t see your unhandled exceptions.  Asserts don\'t suffer from this.</p>\n<p>Also when the exception would be unhandled, a still better practice is to take a mini-dump. One area where VB is more powerful than C# is that you can use an exception filter to snap a mini-dump when the exception is in flight, and leave the rest of the exception handling unchanged.  <a href="http://blogs.msdn.com/greggm/archive/2008/04/21/exception-filter-inject.aspx" rel="nofollow noreferrer">Gregg Miskelly\'s blog post on exception filter inject</a> provides a useful way to do this from c#.</p>\n<p>One other note on assets ... they inteact poorly with Unit testing the error conditions in your code.  It is worthwhile to have a wrapper to turn off the assert for your unit tests.</p>\n'}, {'answer_id': 2033826, 'author': 'Luca', 'author_id': 161554, 'author_profile': 'https://Stackoverflow.com/users/161554', 'pm_score': 0, 'selected': False, 'text': "<p>Here is by 2 cents.</p>\n\n<p>I think that the best way is to use both assertions and exceptions. The main differences between the two methods, imho, if that Assert statements can be removed easily from the application text (defines, conditional attributes...), while Exception thrown are dependent (tipically) by a conditional code which is harder to remove (multine section with preprocessor conditionals).</p>\n\n<p>Every application exception shall be handled correctly, while assertions shall be satisfied only during the algorithm developement and testing.</p>\n\n<p>If you pass an null object reference as routine parameter, and you use this value, you get a null pointer exception. Indeed: why you should write an assertion? It's a waste of time in this case.\nBut what about private class members used in class routines? When these value are set somewhere, is better to check with an assertion if a null value is set. That's only because when you use the member, you get a null pointer exception but you don't know how the value was set. This cause a restart of the program breaking on all entry point use to set the private member.</p>\n\n<p>Exception are more usefull, but they can be (imho) very heavy to manage and there is the possibility to use too much exceptions. And they requires additional check, maybe undesired to optimize the code.\nPersonally I use exceptions only whenever the code requires a deep catch control (catch statements are very low in the call stack) or whenever the function parameters are not hardcoded in the code.</p>\n"}, {'answer_id': 2033938, 'author': 'Mark Simpson', 'author_id': 83891, 'author_profile': 'https://Stackoverflow.com/users/83891', 'pm_score': 3, 'selected': False, 'text': "<p>I've thought about this long and hard when it comes to providing guidance on debug vs. assert with respect to testing concerns.</p>\n\n<p>You should be able to test your class with erroneous input, bad state, invalid order of operations and any other conceivable error condition and an assert should <strong>never</strong> trip.  Each assert is checking something should <strong>always</strong> be true regardless of the inputs or computations performed.  </p>\n\n<p>Good rules of thumb I've arrived at:</p>\n\n<ol>\n<li><p>Asserts are not a replacement for robust code that functions correctly independent of configuration.  They are complementary.</p></li>\n<li><p>Asserts should never be tripped during a unit test run, even when feeding in invalid values or testing error conditions.  The code should handle these conditions without an assert occurring.</p></li>\n<li><p>If an assert trips (either in a unit test or during testing), the class is bugged.  </p></li>\n</ol>\n\n<p>For all other errors -- typically down to environment (network connection lost) or misuse (caller passed a null value) -- it's much nicer and more understandable to use hard checks &amp; exceptions.  If an exception occurs, the caller knows it's likely their fault.  If an assert occurs, the caller knows it's likely a bug in the code where the assert is located.</p>\n\n<p>Regarding duplication: I agree.  I don't see why you would replicate the validation with a Debug.Assert AND an exception check.  Not only does it add some noise to the code and muddy the waters regarding who is at fault, but it a form of repetition.  </p>\n"}, {'answer_id': 5964259, 'author': 'Tim Abell', 'author_id': 10245, 'author_profile': 'https://Stackoverflow.com/users/10245', 'pm_score': 1, 'selected': False, 'text': '<p>Example of a good use of Assert:</p>\n\n<pre><code>Debug.Assert(flibbles.count() &lt; 1000000, "too many flibbles"); // indicate something is awry\nlog.warning("flibble count reached " + flibbles.count()); // log in production as early warning\n</code></pre>\n\n<p>I personally think that Assert should <strong>only</strong> be used when you know something is outside <em>desirable</em> limits, but you can be sure it\'s reasonably safe to continue. In all other circumstances (feel free point out circumstances I haven\'t thought of) use exceptions to fail hard and fast.</p>\n\n<p>The key tradeoff for me is whether you want to bring down a live/production system with an Exception to avoid corruption and make troubleshooting easier, or whether you have encountered a situation that should never be allowed to continue unnoticed in test/debug versions but could be allowed to continue in production (logging a warning of course).</p>\n\n<p>cf. <a href="http://c2.com/cgi/wiki?FailFast" rel="nofollow noreferrer">http://c2.com/cgi/wiki?FailFast</a>\ncopied and modified from java question: <a href="https://stackoverflow.com/questions/1276308/exception-vs-assertion/5963988#5963988">Exception Vs Assertion</a></p>\n'}]
['https://Stackoverflow.com/questions/61219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6004/']