Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net equivalent to Java's AssertionError

In Java, I will occasionally throw an AssertionError directly, to assert that a particular line will not be reached. An example of this would be to assert that the default case in a switch statement cannot be reached (see this JavaSpecialists page for an example).

I would like to use a similar mechanism in .Net. Is there an equivalent exception that I could use? Or is there another method that could be used with the same effect?

Edit - To clarify, I'm looking for a mechanism to flag failures at runtime, in released code, to indicate that there has been a (possibly catastrophic) failure of some invariant in the code. The linked example generates a random integer between 0 and 2 (inclusive) and asserts that the generated number is always 0, 1 or 2. If this assertion doesn't hold, it would be better to stop execution completely rather than continue with some unknown corrupt state of the system.

like image 304
Ben Lings Avatar asked Aug 10 '09 10:08

Ben Lings


1 Answers

I'd normally throw InvalidOperationException or ArgumentOutOfRangeException depending on where the value came from.

Alternatively, there's Debug.Assert (which will only fail when you've got the DEBUG preprocessor symbol defined) or in .NET 4.0 you could use Contract.Fail, Contract.Assert or Contract.Assume depending on the situation. Explicitly throwing an exception has the benefit that the compiler knows that the next statement is unreachable though.

I'm not a big fan of Debug.Assert - it's usually inappropriate for a release (as it throws up an assertion box rather than just failing) and by default it won't be triggered in release anyway. I prefer exceptions which are always thrown, as they prevent your code from carrying on regardless after the opportunity to detect that "stuff is wrong".

Code Contracts changes the game somewhat, as there are all kinds of options for what gets preserved at execution time, and the static checker can help to prove that you won't get into that state. You still need to choose the execution time policy though...

like image 104
Jon Skeet Avatar answered Nov 01 '22 00:11

Jon Skeet