0

is there a way to alter the way the code contracts behave during run time? as in, when a pre or post conidtion fails during run time, the application crashes. Is there a way instead of crashing, have a MessageBox displayed??

H H
  • 263,252
  • 30
  • 330
  • 514
Ari
  • 1,026
  • 6
  • 20
  • 31
  • This post is somewhat vague; I see you've mentioned C# as the reference language, could you give us a sample of code and the actual action vs the desired action? Thanks. – Blaskovicz Oct 29 '11 at 04:27

1 Answers1

2

When a contract fails the program does not 'crash' but an Exception is thrown. The Contracts class lets you control what kind of exception.

So you need some form of Exception Handling, and not just for the Contracts.

Having said that, a failing Contract is usually severe enough to terminate the application.

H H
  • 263,252
  • 30
  • 330
  • 514
  • 1
    +1 for "a failing Contract is usually severe enough to terminate the application". @happyguy: If you are using contracts for every bit of your validation, you might be using it wrong. You should ensure that you pre-validate your values before passing them to a class that will reject them based on its contract. Contract violations are exceptions, and exceptions should be used for exceptional behavior. An example is how you can (and should) check `File.Exists` before opening it, to avoid the `FileNotFoundException`. – Merlyn Morgan-Graham Oct 29 '11 at 09:11
  • 3
    @MerlynMorgan-Graham - You make an excellent point, but your example is not the best. The existance of a file is (usually) not something that is appropriate for a method contract, because the file’s existance is contingent on things outside the control of the program. That is to say, a file can be deleted or moved between the time `File.Exists` is called and the time an attempt is made to open the file. Such things (dubbed "exogenous exceptions" by Eric Lippert) are usually best handled with the ordinary structured exception handling mechanisms. – Jeffrey L Whitledge Nov 03 '11 at 18:52
  • 1
    (continued) Contracts are best for things (like null-reference or integer range checking of by-value parameters) for which the state is known not to change arbitrarily. – Jeffrey L Whitledge Nov 03 '11 at 18:55