Debug.Assert vs. Exception

by Weifen Luo (DevZest) 2. September 2009 17:40

In .Net programming, you can check for a condition and outputs the call stack if the condition is false:

// Test that the index value is valid. 
Debug.Assert(index > -1);

Or throw an exception under a certain condition:

// Test that the index value is valid. 
if (index <= -1)
    throw new ArgumentOutOfRangeException("index");

So the question is: when to use which?

Both Debug.Assert and exception are evaluated against a condition. The key is where the condition come from:

  • Use Debug.Assert if the condition comes from inside of your program (component or application), and your program should not go further with this condition because there is a defect in your program detected already and you should fix it. A triggered Debug.Assert is an effective showstopper of releasing your program.
  • Exceptions are mainly used for component programming. Use exception if the condition comes from outside of your component,  that your program cannot go further with this condition. This does not suggest the defect of your component – the caller of your component should handle this.

The following are some guidelines of Debug.Assert and Exception:

  • Debug.Assert is only available in DEBUG mode: That means you can write as many Debug.Assert as you like, without affect the performance of your release build. However, IMPORTANT: Make sure the condition evaluation never ever modify any of your object state, otherwise you will have two different results for DEBUG and RELEASE build - that could be a nightmare of diagnostics!
  • Exception performance considerations: A significant amount of system resources and execution time are used when you throw or handle an exception. Throw exceptions only to handle truly extraordinary conditions, which you have no control over it since it’s outside your component, not to handle predictable events or flow control.
  • Exception is part of your public contract: If you’re throwing an exception in your component, remember it’s part of your public contract of your component, in addition to the method name and parameter list. This exception is expected to be caught and handled by the caller, so it must be documented together with the method call.
  • Don’t catch general exception: If there is a catch(Exception) line in your code, running visual studio code analysis will give you a Do not catch general exception types error. Please read this blog post for further explanation. BTW, code analysis is a great tool to help you write flawless code, you should run it against all your code!

Tags:

.Net

Comments

9/2/2009 5:43:17 PM #

Debug.Assert vs. Exception

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com |

8/12/2013 1:54:41 PM #

Pingback from com-lab.biz

Make .NET assertion throw an exception in release build | user67

com-lab.biz |

Comments are closed

Copyright DevZest, 2008 - 2014